3.C#编程指南-字符串

字符串是String类型的对象,它的值是文本。在内部,文本被存储为Char对象的顺序只读集合。C#字符串末尾没有以null结尾的字符;因此C#字符串可以包含任意数目的嵌入式null字符(“\0”)。字符串的Length属性代表它包含的Char对象的数量,而不是Unicode字符的数量。若要访问字符串中的各个Unicode码位,请使用StringInfo对象。在C#中,string关键字是String的别名。

声明和初始化字符串

View Code
//1.声明字符串,没有初始化
string message1;

//2.使用null初始化字符串
string message2 = null;

//3.使用Empty初始化字符串,可新建字符串长度为零的String对象。
//零长度字符串的字符串表示形式为""。
//使用Empty值(而不是null)初始化字符串可以降低发生NullReferenceException的可能性
string message3 = String.Empty;

//4.初始化一个普通的字符串
string oldPath = "c:\\Program Files\\Microsoft";

//5.初始化一个逐字字符串
string newPath = @"c:\Program Files\Microsoft";

//6.本地变量(即在方法体),你可以使用隐式类型。
var temp = "I'm still a ...";

//7.除了在使用字符数组初始化字符串以外,不要使用new运算符创建字符串对象。
char[] letters = {'A','B','C'};
string alphabet = new string(letters);


字符串对象的不可变性

 字符串对象是不可变的:即它们创建之后就无法更改。所以看似修改字符串的String方法和C#运算符实际上都以新字符串对象的形式返回结果。

View Code
//在下面的示例中,当连接s1和s2的内容形成一个字符串时,不会修改两个原始字符串。
//+=运算符会创建一个包含组合内容的新字符串。这个新对象赋给变量s1,而最初赋给
//s1的对象由于没有其他任何变量包含对它的引用而释放,用于垃圾回收。
string s1 = "A string is more";
string s2 = "than the sum of its chars.";
s1 += s2;
System.Console.WriteLine(s1);
//Output:A string is more than the sum of its chars.

由于“修改”字符串实际上是创建新字符串,因些创建字符串的引用时必须谨慎。如果创建了对字符串的引用,然后“修改”原始字符串,则该引用指向的仍是原始对象,而不是修改字符串时创建的新对象。

View Code
string s1 = "Hello";
string s2 = s1;
s1 += "World";
System.Console.WriteLine(s2);
//Output:Hello


普通字符串和原义字符串

如果必须嵌入C#提供的转义符,则应使用普通字符串:

View Code
string columns = "Column 1\tColumn 2\tColumn 3";
//Output: Column 1 Column 2 Column 3

string rows = "Row 1\r\nRow 2\r\nRow 3";
/* Output:
Row 1
Row 2
Row 3
*/

string title = "\"The \u00C6olean Harp\", by Samuel Taylor Coleridge";
//Output: "The Æolean Harp", by Samuel Taylor Coleridge

如果字符串文本包含反斜杠字符,为方便起见和提高可读性,应使用原义字符串。由于原义字符串保留换行符作为字符串文本的一部分,因此可用于初始化多行字符串。

在原义字符串中嵌入引号时请使用双引号

View Code
string filePath = @"C:\Users\scoleridge\Documents\";
//Output: C:\Users\scoleridge\Documents\

string text = @"My pensive SARA ! thy soft cheek reclined
Thus on mine arm, most soothing sweet it is
To sit beside our Cot,...
";
/* Output:
My pensive SARA ! thy soft cheek reclined
Thus on mine arm, most soothing sweet it is
To sit beside our Cot,...
*/

string quote = @"Her name was ""Sara.""";
//Output: Her name was "Sara."


格式字符串
格式字符串是内容可以在运行时动态确定的一种字符串。采用以下方式创建格式字符串:使用静态Format方法并在大括号中嵌入占位符,这些占位符将在运行时替换为其他值。

string s = String.Format("{0} World!","Hello");
Console.WriteLine(s);

WriteLine方法的一个重载将格式字符串用作参数。因此,可以只嵌入格式字符串,而无需显式调用该方法。但若使用WriteLine方法在Visual Studio“输出”窗口中显示

调试输出,则必须显式调用Format方法,因为WriteLine只接受字符串,而不接受格式字符串。

子字符串

子字符串是包含在字符串中的任意字符序列。

使用SubString方法可以基于原始字符串的一部分创建新字符串。

可以使用IndexOf方法搜索子字符串的一个或多个匹配项。

使用Replace方法可将指定子字符串的所有匹配项替换为一个新字符串。

与SubString方法一样,Replace实际上返回的也是新字符串,而不修改原始字符串。

 

访问各个字符

可以使用带索引值的数组表示法获取对各个字符的只读访问

View Code
string s5 = "Printing backwards";
for(int i = 0; i < s5.Length; i++)
{
System.Console.Write(s5[s5.Length - i - 1]);
}
//Output:"sdrawkcab gnitnirP"

可以使用StringBuilder对象修改各个字符

View Code
string question = "hOW DOES mICROSOFT wORD DEAL WITH THE cAPS lOCK KEY?";
System.Text.StringBuilder sb = new System.Text.StringBuilder(question);

for (int j = 0; j < sb.Length; j++)
{
if (System.Char.IsLower(sb[j]) == true)
{
sb[j] = System.Char.ToUpper(sb[j]);
}
else if (System.Char.IsUpper(sb[j]) == true)
{
sb[j] = System.Char.ToLower(sb[j]);
}
}
// Store the new string.
string corrected = sb.ToString();
System.Console.WriteLine(corrected);
// Output: How does Microsoft Word deal with the Caps Lock key?


Null字符串和空字符串

空字符串是不包含字符的System.String对象的实例。可以对空字符串调用方法,因为它们是有效的System.String对象。

string s = String.Empty;

null字符串并不引用System.String对象的实例,任何对null字符串调用方法的尝试都会生成NullReferenceException。

但是,可以在串联和比较操作中将null字符串与其他字符串一起使用。

View Code
static void Main()
{
string str = "hello";
string nullStr = null;
string emptyStr = String.Empty;

string tempStr = str + nullStr;
// The following line displays "hello."
Console.WriteLine(tempStr);

bool b = (emptyStr == nullStr);
// The following line displays False.
Console.WriteLine(b);

// The following line creates a new empty string.
string newStr = emptyStr + nullStr;

// Null strings and empty strings behave differently. The following
// two lines display 0.
Console.WriteLine(emptyStr.Length);
Console.WriteLine(newStr.Length);
// The following line raises a NullReferenceException.
//Console.WriteLine(nullStr.Length);

// The null character can be displayed and counted, like other chars.
string s1 = "\x0" + "abc";
string s2 = "abc" + "\x0";
// The following line displays "* abc*".
Console.WriteLine("*" + s1 + "*");
// The following line displays "*abc *".
Console.WriteLine("*" + s2 + "*");
// The following line displays 4.
Console.WriteLine(s2.Length);
}

 

posted on 2012-04-06 16:56  YeChun  阅读(255)  评论(0编辑  收藏  举报

导航