更新:2007 年 11 月
C# 字串是使用 string 關鍵字宣告的一個或多個字元的群組,這個關鍵字是 System.String 類別的 C# 語言捷徑。C# 的字串比 C 或 C++ 的字元陣列更容易使用,而且更不容易產生程式設計錯誤。
字串常值則使用引號宣告,如同下列範例所示:
string greeting = "Hello, World!";
您可以擷取子字串然後結合字串,如下所示:
string s1 = "A string is more ";
string s2 = "than the sum of its chars.";
// Concatenate s1 and s2. This actually creates a new
// string object and stores it in s1, releasing the
// reference to the original object.
s1 += s2;
System.Console.WriteLine(s1);
// Output: A string is more than the sum of its chars.
字串物件是不變的,一旦建立就無法變更。在字串上作用的方法會實際傳回新的字串物件。因此基於效能考量,應讓 StringBuilder 類別執行大量串連動作,或是其他相關的字串管理,如底下的程式碼範例所示。
使用字串
逸出字元
像是 "\n" (新增一行) 和 "\t" (定位鍵) 的逸出字元可包含在字串中。程式碼行:
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
與下列相同:
Hello
World!
如果您要包含反向斜線,在反向斜線之前必須有另一個反向斜線。下列字串:
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."
實際上與下列相同:
\\My Documents\
@ 符號
@ 符號指定在字串建立時必須忽略逸出字元 (Escape Character) 和分行符號。因此下列兩個字串是完全相同的:
string p1 = "\\\\My Documents\\My Files\\";
string p2 = @"\\My Documents\My Files\";
ToString()
C# 內建資料型別都提供 ToString 方法將數值轉換成字串。這個方法可用來將數值轉換成字串,如下所示:
int year = 1999;
string msg = "Eve was born in " + year.ToString();
System.Console.WriteLine(msg); // outputs "Eve was born in 1999"
存取個別字元
您可以使用像是 Substring、Replace、Split 和 Trim 方法存取字串中包含的個別字元。
string s3 = "Visual C# Express";
System.Console.WriteLine(s3.Substring(7, 2));
// Output: "C#"
System.Console.WriteLine(s3.Replace("C#", "Basic"));
// Output: "Visual Basic Express"
// Index values are zero-based
int index = s3.IndexOf("C");
// index = 7
也可能將字元複製到字元陣列中,如下所示:
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?
您可以使用索引存取字串中的個別字元,如下所示:
string s5 = "Printing backwards";
for (int i = 0; i < s5.Length; i++)
{
System.Console.Write(s5[s5.Length - i - 1]);
}
// Output: "sdrawkcab gnitnirP"
變更大小寫
若要將字串中的字母變更為大寫或小寫,請使用 ToUpper() 或 ToLower(),如下所示:
string s6 = "Battle of Hastings, 1066";
System.Console.WriteLine(s6.ToUpper());
// outputs "BATTLE OF HASTINGS 1066"
System.Console.WriteLine(s6.ToLower());
// outputs "battle of hastings 1066"
比較
比較兩個非當地語系化字串的最佳方式是使用 Equals 方法搭配 StringComparison.Ordinal 和 StringComparison.OrdinalIgnoreCase。
// Internal strings that will never be localized.
string root = @"C:\users";
string root2 = @"C:\Users";
// Use the overload of the Equals method that specifies a StringComparison.
// Ordinal is the fastest way to compare two strings.
bool result = root.Equals(root2, StringComparison.Ordinal);
Console.WriteLine("Ordinal comparison: {0} and {1} are {2}", root, root2,
result ? "equal." : "not equal.");
// To ignore case means "user" equals "User". This is the same as using
// String.ToUpperInvariant on each string and then performing an ordinal comparison.
result = root.Equals(root2, StringComparison.OrdinalIgnoreCase);
Console.WriteLine("Ordinal ignore case: {0} and {1} are {2}", root, root2,
result ? "equal." : "not equal.");
// A static method is also available.
bool areEqual = String.Equals(root, root2, StringComparison.Ordinal);
// String interning. Are these really two distinct objects?
string a = "The computer ate my source code.";
string b = "The computer ate my source code.";
// ReferenceEquals returns true if both objects
// point to the same location in memory.
if (String.ReferenceEquals(a, b))
Console.WriteLine("a and b are interned.");
else
Console.WriteLine("a and b are not interned.");
// Use String.Copy method to avoid interning.
string c = String.Copy(a);
if (String.ReferenceEquals(a, c))
Console.WriteLine("a and c are interned.");
else
Console.WriteLine("a and c are not interned.");
字串物件也有根據一個字串是否小於 (<) 或大於 (>) 另一個字串,而傳回整數值的 CompareTo() 方法。比較字串時會使用 Unicode 值,而小寫的值比大寫的小。
// Enter different values for string1 and string2 to
// experiement with behavior of CompareTo
string string1 = "ABC";
string string2 = "abc";
int result2 = string1.CompareTo(string2);
if (result2 > 0)
{
System.Console.WriteLine("{0} is greater than {1}", string1, string2);
}
else if (result2 == 0)
{
System.Console.WriteLine("{0} is equal to {1}", string1, string2);
}
else if (result2 < 0)
{
System.Console.WriteLine("{0} is less than {1}", string1, string2);
}
// Output: ABC is less than abc
若要在另一個字串中搜尋字串,請使用 IndexOf()。如果找不到搜尋字串,IndexOf() 會傳回 -1,否則,會傳回第一個發生位置之以零起始的索引。
// Date strings are interpreted according to the current culture.
// If the culture is en-US, this is interpreted as "January 8, 2008",
// but if the user's computer is fr-FR, this is interpreted as "August 1, 2008"
string date = "01/08/2008";
DateTime dt = Convert.ToDateTime(date);
Console.WriteLine("Year: {0}, Month: {1}, Day: {2}", dt.Year, dt.Month, dt.Day);
// Specify exactly how to interpret the string.
IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);
// Alternate choice: If the string has been input by an end user, you might
// want to format it according to the current culture:
// IFormatProvider culture = System.Threading.Thread.CurrentThread.CurrentCulture;
DateTime dt2 = DateTime.Parse(date, culture, System.Globalization.DateTimeStyles.AssumeLocal);
Console.WriteLine("Year: {0}, Month: {1}, Day {2}", dt2.Year, dt2.Month, dt2.Day);
/* Output (assuming first culture is en-US and second is fr-FR):
Year: 2008, Month: 1, Day: 8
Year: 2008, Month: 8, Day 1
*/
將字串分隔為子字串
將字串分隔為子字串 (例如,將句子分隔為個別文字) 是常見的程式設計工作。Split() 方法使用分隔符號 (例如,空白字元) 的 char 陣列,並且傳回子字串陣列。您可以用 foreach 存取這個陣列,如下所示:
string numString = "1287543"; //"1287543.0" will return false for a long
long number1 = 0;
bool canConvert = long.TryParse(numString, out number1);
if (canConvert == true)
Console.WriteLine("number1 now = {0}", number1);
else
Console.WriteLine("numString is not a valid long");
byte number2 = 0;
numString = "255"; // A value of 256 will return false
canConvert = byte.TryParse(numString, out number2);
if (canConvert == true)
Console.WriteLine("number2 now = {0}", number2);
else
Console.WriteLine("numString is not a valid byte");
decimal number3 = 0;
numString = "27.3"; //"27" is also a valid decimal
canConvert = decimal.TryParse(numString, out number3);
if (canConvert == true)
Console.WriteLine("number3 now = {0}", number3);
else
Console.WriteLine("number3 is not a valid decimal");
這個程式碼會在不同的行輸出每個文字,如下所示:
The
cat
sat
on
the
mat.
使用 StringBuilder
如果程式執行大量字串管理,StringBuilder 類別會建立字串緩衝區以提供更好的效能。StringBuilder 類別也可以讓您重新指派內建字串資料型別不支援的某些個別字元。
在這個範例中會建立 StringBuilder 物件,並且使用 Append 方法逐一加入內容。
class TestStringBuilder
{
static void Main()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
// Create a string composed of numbers 0 - 9
for (int i = 0; i < 10; i++)
{
sb.Append(i.ToString());
}
System.Console.WriteLine(sb); // displays 0123456789
// Copy one character of the string (not possible with a System.String)
sb[0] = sb[9];
System.Console.WriteLine(sb); // displays 9123456789
}
}