字串的操作一直是各語言的重頭戲,本文主要介紹C#常用操作字串的方法,以供有興趣的朋友參考。


C# 使用 string 來宣告字元陣列。其常值使用雙引號來高告。
string str1 = “Hello, ”;
string str2 = “C#”;
str1 += str2;
System.Console.WriteLine(str1);    // outputs: Hello, C#
 
常使用這種方式來結合字串,但是C#的字串為物件,一旦建立後就無法改變。這樣的結果會產生一堆字串物件,會產生一堆字串物件,基於效能的考量,,這時需改用 StringBuilder class 來進行大量的字串處理。
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(“str1 “);
sb.Append(“str2 “).Append(“str3”);
string str = sb.ToString();
 
NOTE: 在建立字串參考時要特別注意,當建立字串參考後,修改原字串的值,此參考會指向原字串的原始物件,而不是指向新修改的物件。
string str1 = “test”;
string str2 = str1;
str1 += “123”;
System.Console.WriteLine(str2);    // outputs: test
 
使用字串
逸出字元和大五碼的中文字常常都是字串在使用上需特別注意的地方,此時反斜線(\)會有超出常人的功用在。
 
@符號會告訴字串建構函式忽略逸出字元和分行符號。因此下列兩個字串是完全相同的:
string p1 = "\\\\My Documents\\My Files\\";
string p2 = @"\\My Documents\My Files\";
 
@ tips is multi-line strings in C#
string str = @”select *
                        from txn
                        where bb=2”;
 
ToString()用來將數值轉換成字串。
int year = 2010;
string msg = "Happy New Year " + year.ToString();
System.Console.WriteLine(msg);  // outputs "Happy New Year 2010"
 
Null 字串和空字串
Null string 不是 System.String Object的執行個體(instance),當你嘗試去使用 Null string 的方法時,將導致 NullReferenceException
string nullStr = null;
int len = nullStr.Length();         // throws NullReferenceException
空字串是 System.String Object的執行個體,包含零個字元。空字串初始化如下:
string str = “”;
 
常用的字串使用方法
Length() 取回字串長度。
 
Split() 傳回字串陣列,其中每個項目都是文字。
MSDN Example:
class TestStringSplit
{
    static void Main()
    {
        char[] delimiterChars = { ' ', ',', '.', ':', '\t' };
 
        string text = "one\ttwo three:four,five six seven";
        System.Console.WriteLine("Original text: '{0}'", text);
 
        string[] words = text.Split(delimiterChars);
        System.Console.WriteLine("{0} words in text:", words.Length);
 
        foreach (string s in words)
        {
            System.Console.WriteLine(s);
        }
    }
}
 
Output:
Original text: 'one     two three:four,five six seven'
7 words in text:
one
two
three
four
five
six
seven
 
搜尋字串內容
string 提供許多有用的方法來搜尋字串內容。下列範例使用了 IndexOf()LastIndexOf()StartsWith() EndsWith() 方法。
MSDN Example:
class StringSearch
{
    static void Main()
    {
        string str = "A silly sentence used for silly purposes.";
        System.Console.WriteLine("'{0}'",str);
 
        bool test1 = str.StartsWith("a silly");
        System.Console.WriteLine("starts with 'a silly'? {0}", test1);
 
        bool test2 = str.StartsWith("a silly", System.StringComparison.OrdinalIgnoreCase);
        System.Console.WriteLine("starts with 'a silly'? {0} (ignoring case)", test2);
 
        bool test3 = str.EndsWith(".");
        System.Console.WriteLine("ends with '.'? {0}", test3);
 
        int first = str.IndexOf("silly");
        int last = str.LastIndexOf("silly");
        string str2 = str.Substring(first, last - first);
        System.Console.WriteLine("between two 'silly' words: '{0}'", str2);
    }
}
 
Output:
'A silly sentence used for silly purposes.'
starts with 'a silly'? False
starts with 'a silly'? True (ignore case)
ends with '.'? True
between two 'silly' words: 'silly sentence used for '
 
連結多個字串
連結字串有兩種方法:
1.      使用 + 運算子。優點是非常容易使用,撰寫程式碼容易;缺點是會產生好多字串,造成效能問題。
string two = "two";
string str = "one " + two + " three";
System.Console.WriteLine(str);


      上面程式碼共產生了五個字串。
 
2.      使用 StringBuilder class Append 方法來連結字串,不會產生 + 運算子的問題。
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(“str1 “);
sb.Append(“str2 “).Append(“str3”);
string str = sb.ToString();
System.Console.WriteLine(str);
 
修改字串內容
字串是「不可變動的」(Immutable),所以不可能修改字串內容。然而,字串的內容可抽取至非不可變動的表單、進行修改,然後形成新的字串執行個體。
MSDN Example:
class ModifyStrings
{
    static void Main()
    {
        string str = "The quick brown fox jumped over the fence";
        System.Console.WriteLine(str);
 
        char[] chars = str.ToCharArray();
        int animalIndex = str.IndexOf("fox");
        if (animalIndex != -1)
        {
            chars[animalIndex++] = 'c';
            chars[animalIndex++] = 'a';
            chars[animalIndex] = 't';
        }
 
        string str2 = new string(chars);
        System.Console.WriteLine(str2);
    }
}
 
Output:
The quick brown fox jumped over the fence
The quick brown cat jumped over the fence
 
說明:
1. 使用 ToCharArray  方法將字串內容抽取至 char  型別的陣列。
2. 修改此陣列中的某些項目。

3. 使用 char 陣列建立新的字串執行個體。

arrow
arrow
    文章標籤
    C# String
    全站熱搜

    mark528 發表在 痞客邦 留言(0) 人氣()