码迷,mamicode.com
首页 > Windows程序 > 详细

C#中字符串String类及方法的使用(一)

时间:2014-12-12 12:58:31      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   ar   color   os   使用   sp   for   

一、实例化String对象


1、最常用的方法是直接将字符串分配到String变量中。

 注意1:转义字符 \ ,字符串内含有引号""、反斜杠\或换行等都需要使用“\”输出。

 注意2:在字符串前面使用@符号,指明转义序列不被处理。

 1 string string1 = "This is a string created by assignment.";
 2 Console.WriteLine(string1);
 3 string string2a = "The path is C:\\PublicDocuments\\Report1.doc";
 4 Console.WriteLine(string2a);
 5 string string2b = @"The path is C:\PublicDocuments\Report1.doc";
 6 Console.WriteLine(string2b);
 7 // 显示结果:
 8 //       This is a string created by assignment.
 9 //       The path is C:\PublicDocuments\Report1.doc
10 //       The path is C:\PublicDocuments\Report1.doc    

 2、使用String构造函数。

 我们可以将一个Unicode字符数组实例化,使用:

 String(Char[])  String(Char*)  String(SByte*)

 或者将某个字符重复多遍实例化使用:

String(Char, Int32)

 再者将一个Unicode字符数组中的一部分实例化使用:

String(Char*, Int32, Int32)  String(Char[], Int32, Int32)  String(SByte*, Int32, Int32)

 1             char[] chars = { w, o, r, d };
 2             sbyte[] bytes = { 0x41, 0x42, 0x43, 0x44, 0x45, 0x00 };
 3 
 4             // 通过字符数组实例化一个字符串.
 5             string string1 = new string(chars);
 6             Console.WriteLine(string1);
 7 
 8             string stringFromBytes = null;
 9             string stringFromChars = null;
10             unsafe
11             {
12                 fixed (sbyte* pbytes = bytes)
13                 {
14                     // 通过byte数组指针实例化一个字符串.
15                     stringFromBytes = new string(pbytes);
16                 }
17                 fixed (char* pchars = chars)
18                 {
19                     // 通过字符数组指针实例化一个字符串.
20                     stringFromChars = new string(pchars);
21                 }
22             }
23             Console.WriteLine(stringFromBytes);
24             Console.WriteLine(stringFromChars);
25 
26             // 实例化一个由20个c组成的字符串.
27             string string2 = new string(c, 20);
28             Console.WriteLine(string2);
29 
30             //将字符数组中第1个字母(从0开始)起长度为2的字符串实例化
31             string string3 = new string(chars, 1, 2);
32             Console.WriteLine(string3);
33             // 显示结果:
34             //       word
35             //       ABCDE
36             //       word
37             //       ccccccccccccccccccccc
38             //       or            

二、String类属性


  • Chars获取当前 String 对象中位于指定位置的 Char 对象。
  • Length  获取当前 String 对象中的字符数,即字符串长度。
1 string str1 = "Test";
2 for (int ctr = 0; ctr <= str1.Length - 1; ctr++)
3     Console.Write("{0} ", str1[ctr]);
4 //显示结果:
5 //      T e s t

 


参考:http://msdn.microsoft.com/zh-cn/library/chfa2zb8(VS.80).aspx

C#中字符串String类及方法的使用(一)

标签:style   blog   http   ar   color   os   使用   sp   for   

原文地址:http://www.cnblogs.com/miemie/p/4157448.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!