C#字串

在 C# 中,使用字串作為字元數組,但更常見的做法是使用string關鍵字來聲明一個字串變數。string關鍵字是System.String類的別名。

創建一個字串對象

可以使用以下方法之一來創建字串對象:

  • 通過將一個字串文字分配給一個String變數
  • 通過使用String類構造函數
  • 通過使用字串連接運算符(+)
  • 通過檢索屬性或調用返回字串的方法
  • 通過調用格式化方法將值或對象轉換為其字串表示形式

示例:

using System;
namespace StringApplication
{
   class Program
   {
      static void Main(string[] args)
      {
         //from string literal and string concatenation
         string fname, lname;
         fname = "Rowan";
         lname = "Atkinson";

         string fullname = fname + lname;
         Console.WriteLine("Full Name: {0}", fullname);

         //by using string constructor
         char[] letters = { 'H', 'e', 'l', 'l','o' };
         string greetings = new string(letters);
         Console.WriteLine("Greetings: {0}", greetings);

         //methods returning string
         string[] sarray = { "Hello", "From", "zaixian", "Point" };
         string message = String.Join(" ", sarray);
         Console.WriteLine("Message: {0}", message);

         //formatting method to convert a value
         DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1);
         string chat = String.Format("Message sent at {0:t} on {0:D}", waiting);
         Console.WriteLine("Message: {0}", chat);
      }
   }
}

當編譯和執行上述代碼時,會產生以下結果:

Full Name: Rowan Atkinson
Greetings: Hello
Message: Hello From zaixian Point
Message: Message sent at 5:58 PM on Wednesday, October 10, 2012

String類的屬性

String類具有以下兩個屬性:

編號 屬性 說明
1 Chars 獲取當前String對象中指定位置的Char對象。
2 Length 獲取當前String對象中的字元數。

String類的方法

String類有許多方法可以幫助我們來處理字串對象。下表中提供了一些最常用的方法:

編號 方法 說明
1 public static int Compare(string strA, string strB) 比較兩個指定的字串對象,並返回一個整數,指示其在排序順序中的相對位置。
2 public static int Compare(string strA, string strB, bool ignoreCase ) 比較兩個指定的字串對象,並返回一個整數,指示其在排序順序中的相對位置。 但是,如果布爾參數為真,它將忽略大小寫。
3 public static string Concat(string str0, string str1) 連接兩個字串對象。
4 public static string Concat(string str0, string str1, string str2) 連接三個字串對象。
5 public static string Concat(string str0, string str1, string str2, string str3) 連接四個字串對象。
6 public bool Contains(string value) 返回一個值,該值指示在此字串中是否發生指定的String對象。
7 public static string Copy(string str) 創建與指定字串相同值的新String對象。
8 public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) 將指定數量的字元從String對象的指定位置複製到Unicode字元數組中的指定位置。
9 public bool EndsWith(string value) 確定字串對象的末尾是否與指定的字串匹配。
10 public bool Equals(string value) 確定當前的String對象和指定的String對象是否具有相同的值。
11 public static bool Equals(string a, string b) 確定兩個指定的String對象是否具有相同的值。
12 public static string Format(string format, Object arg0) 用指定對象的字串表示替換指定字串中的一個或多個格式項。
13 public int IndexOf(char value) 返回當前字串中指定Unicode字元首次出現的從零開始的索引。
14 public int IndexOf(string value) 返回此實例中指定字串第一次出現的從零開始的索引。
15 public int IndexOf(char value, int startIndex) 返回此字串中指定Unicode字元第一次出現的從零開始的索引,在指定的字元位置開始搜索。
16 public int IndexOf(string value, int startIndex) 返回此實例中指定字串第一次出現的從零開始的索引,在指定的字元位置開始搜索。
17 public int IndexOfAny(char[] anyOf) 返回指定Unicode字元數組中任何字元在此實例中第一次出現的基於零的索引。
18 public int IndexOfAny(char[] anyOf, int startIndex) 返回在指定的Unicode字元數組中的任何字元在這個實例的第一次出現的基於零的索引,在指定的字元位置開始搜索。
19 public string Insert(int startIndex, string value) 返回一個新的字串,在當前字串對象的指定索引位置插入指定的字串。
20 public static bool IsNullOrEmpty(string value) 判斷指定的字串是空值還是空字元串。
21 public static string Join(string separator, params string[] value) 每個元素之間使用指定的分隔符號來連接字串數組的所有元素。
22 public static string Join(string separator, string[] value, int startIndex, int count) 每個元素之間使用指定的分隔符號來連接字串數組的指定元素。
23 public int LastIndexOf(char value) 返回當前字串對象中指定Unicode字元,從零開始搜索的最後一次出現的索引位置。
24 public int LastIndexOf(string value) 返回當前字串對象中指定字串從零開始搜索的最後一次出現的索引位置。
25 public string Remove(int startIndex) 刪除當前實例中從指定位置開始到最後一個位置的所有字元,並返回此字串。
26 public string Remove(int startIndex, int count) 從指定位置移除當前字串中指定數量的字元,並返回字串。
27 public string Replace(char oldChar, char newChar) 使用指定的Unicode字元替換當前字串對象中指定的Unicode字元的所有出現字元,並返回新的字串。
28 public string Replace(string oldValue, string newValue) 使用指定的字串替換當前字串對象中指定字串的所有出現字元,並返回新的字串。
29 public string[] Split(params char[] separator) 返回一個字串數組,其中包含當前字串對象中的子字串,由指定的Unicode字元數組的元素分隔。
30 public string[] Split(char[] separator, int count) 返回一個字串數組,其中包含當前字串對象中的子字串,由指定的Unicode字元數組的元素分隔。 int參數指定要返回的子字串的最大數量。
31 public bool StartsWith(string value) 確定此字串實例的開始是否與指定的字串匹配。
32 public char[] ToCharArray() 返回一個Unicode字元數組,其中包含當前字串對象中的所有字元。
33 public char[] ToCharArray(int startIndex, int length) 返回一個Unicode字元數組,其中包含當前字串對象中的所有字元(從指定的索引開始,直到指定的長度。)
34 public string ToLower() 返回一個轉換為小寫的字串的副本。
35 public string ToUpper() 返回一個轉換為大寫的字串的副本。
36 public string Trim() 從當前String對象中刪除所有前導和尾隨的空格字元。

您可以訪問MSDN庫,獲取方法和String類構造函數的完整列表。

實例

以下示例演示了上述一些方法:

比較字串:

using System;
namespace StringApplication
{
   class StringProg
   {
      static void Main(string[] args)
      {
         string str1 = "This is test";
         string str2 = "This is text";

         if (String.Compare(str1, str2) == 0)
         {
            Console.WriteLine(str1 + " and " + str2 +  " are equal.");
         }
         else
         {
            Console.WriteLine(str1 + " and " + str2 + " are not equal.");
         }
         Console.ReadKey() ;
      }
   }
}

當編譯和執行上述代碼時,會產生以下結果:

This is test and This is text are not equal.

字串包含字串:

using System;
namespace StringApplication
{
   class StringProg
   {
      static void Main(string[] args)
      {
         string str = "This is test";
         if (str.Contains("test"))
         {
            Console.WriteLine("The sequence 'test' was found.");
         }
         Console.ReadKey() ;
      }
   }
}

當編譯和執行上述代碼時,會產生以下結果:

The sequence 'test' was found.

獲取子字串:

using System;
namespace StringApplication
{
   class StringProg
   {
      static void Main(string[] args)
      {
         string str = "Last night I dreamt of Girls";
         Console.WriteLine(str);
         string substr = str.Substring(23);
         Console.WriteLine(substr);
      }
   }
}

當編譯和執行上述代碼時,會產生以下結果:

Girls

將字串連接:

using System;
namespace StringApplication
{
   class StringProg
   {
      static void Main(string[] args)
      {
         string[] starray = new string[]{"Down the way nights are dark",
         "And the sun shines daily on the mountain top",
         "I took a trip on a sailing ship",
         "And when I reached Jamaica",
         "I made a stop"};

         string str = String.Join("\n", starray);
         Console.WriteLine(str);
      }
   }
}

當編譯和執行上述代碼時,會產生以下結果:

Down the way nights are dark
And the sun shines daily on the mountain top
I took a trip on a sailing ship
And when I reached Jamaica
I made a stop

上一篇: C#數組 下一篇: C#結構體