C# 字串(String)

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

創建 String 對象

您可以使用以下方法之一來創建 string 對象:

  • 通過給 String 變數指定一個字串
  • 通過使用 String 類構造函數
  • 通過使用字串串聯運算符( + )
  • 通過檢索屬性或調用一個返回字串的方法
  • 通過格式化方法來轉換一個值或對象為它的字串表示形式

下麵的實例演示了這點:

實例

using System;

namespace StringApplication
{
    class Program
    {
        static void Main(string[] args)
        {
           //字串,字串連接
            string fname, lname;
            fname = "Rowan";
            lname = "Atkinson";

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

            //通過使用 string 構造函數
            char[] letters = { 'H', 'e', 'l', 'l','o' };
            string greetings = new string(letters);
            Console.WriteLine("Greetings: {0}", greetings);

            //方法返回字串
            string[] sarray = { "Hello", "From", "Tutorials", "Point" };
            string message = String.Join(" ", sarray);
            Console.WriteLine("Message: {0}", message);

            //用於轉化值的格式化方法
            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);
            Console.ReadKey() ;
        }
    }
}

當上面的代碼被編譯和執行時,它會產生下列結果:

Full Name: RowanAtkinson
Greetings: Hello
Message: Hello From Tutorials Point
Message: Message sent at 17:58 on Wednesday, 10 October 2012

String 類的屬性

String 類有以下兩個屬性:

序號屬性名稱 & 描述
1Chars
在當前 String 對象中獲取 Char 對象的指定位置。
2Length
在當前的 String 對象中獲取字元數。

String 類的方法

String 類有許多方法用於 string 對象的操作。下麵的表格提供了一些最常用的方法:

序號方法名稱 & 描述
1public static int Compare( string strA, string strB )
比較兩個指定的 string 對象,並返回一個表示它們在排列順序中相對位置的整數。該方法區分大小寫。
2public static int Compare( string strA, string strB, bool ignoreCase )
比較兩個指定的 string 對象,並返回一個表示它們在排列順序中相對位置的整數。但是,如果布爾參數為真時,該方法不區分大小寫。
3public static string Concat( string str0, string str1 )
連接兩個 string 對象。
4public static string Concat( string str0, string str1, string str2 )
連接三個 string 對象。
5public static string Concat( string str0, string str1, string str2, string str3 )
連接四個 string 對象。
6public bool Contains( string value )
返回一個表示指定 string 對象是否出現在字串中的值。
7public static string Copy( string str )
創建一個與指定字串具有相同值的新的 String 對象。
8public void CopyTo( int sourceIndex, char[] destination, int destinationIndex, int count )
從 string 對象的指定位置開始複製指定數量的字元到 Unicode 字元數組中的指定位置。
9public bool EndsWith( string value )
判斷 string 對象的結尾是否匹配指定的字串。
10public bool Equals( string value )
判斷當前的 string 對象是否與指定的 string 對象具有相同的值。
11public static bool Equals( string a, string b )
判斷兩個指定的 string 對象是否具有相同的值。
12public static string Format( string format, Object arg0 )
把指定字串中一個或多個格式項替換為指定對象的字串表示形式。
13public int IndexOf( char value )
返回指定 Unicode 字元在當前字串中第一次出現的索引,索引從 0 開始。
14public int IndexOf( string value )
返回指定字串在該實例中第一次出現的索引,索引從 0 開始。
15public int IndexOf( char value, int startIndex )
返回指定 Unicode 字元從該字串中指定字元位置開始搜索第一次出現的索引,索引從 0 開始。
16public int IndexOf( string value, int startIndex )
返回指定字串從該實例中指定字元位置開始搜索第一次出現的索引,索引從 0 開始。
17public int IndexOfAny( char[] anyOf )
返回某一個指定的 Unicode 字元數組中任意字元在該實例中第一次出現的索引,索引從 0 開始。
18public int IndexOfAny( char[] anyOf, int startIndex )
返回某一個指定的 Unicode 字元數組中任意字元從該實例中指定字元位置開始搜索第一次出現的索引,索引從 0 開始。
19public string Insert( int startIndex, string value )
返回一個新的字串,其中,指定的字串被插入在當前 string 對象的指定索引位置。
20public static bool IsNullOrEmpty( string value )
指示指定的字串是否為 null 或者是否為一個空的字串。
21public static string Join( string separator, string[] value )
連接一個字串數組中的所有元素,使用指定的分隔符號分隔每個元素。
22public static string Join( string separator, string[] value, int startIndex, int count )
連接接一個字串數組中的指定位置開始的指定元素,使用指定的分隔符號分隔每個元素。
23public int LastIndexOf( char value )
返回指定 Unicode 字元在當前 string 對象中最後一次出現的索引位置,索引從 0 開始。
24public int LastIndexOf( string value )
返回指定字串在當前 string 對象中最後一次出現的索引位置,索引從 0 開始。
25public string Remove( int startIndex )
移除當前實例中的所有字元,從指定位置開始,一直到最後一個位置為止,並返回字串。
26public string Remove( int startIndex, int count )
從當前字串的指定位置開始移除指定數量的字元,並返回字串。
27public string Replace( char oldChar, char newChar )
把當前 string 對象中,所有指定的 Unicode 字元替換為另一個指定的 Unicode 字元,並返回新的字串。
28public string Replace( string oldValue, string newValue )
把當前 string 對象中,所有指定的字串替換為另一個指定的字串,並返回新的字串。
29public string[] Split( params char[] separator )
返回一個字串數組,包含當前的 string 對象中的子字串,子字串是使用指定的 Unicode 字元數組中的元素進行分隔的。
30public string[] Split( char[] separator, int count )
返回一個字串數組,包含當前的 string 對象中的子字串,子字串是使用指定的 Unicode 字元數組中的元素進行分隔的。int 參數指定要返回的子字串的最大數目。
31public bool StartsWith( string value )
判斷字串實例的開頭是否匹配指定的字串。
32public char[] ToCharArray()
返回一個帶有當前 string 對象中所有字元的 Unicode 字元數組。
33public char[] ToCharArray( int startIndex, int length )
返回一個帶有當前 string 對象中所有字元的 Unicode 字元數組,從指定的索引開始,直到指定的長度為止。
34public string ToLower()
把字串轉換為小寫並返回。
35public string ToUpper()
把字串轉換為大寫並返回。
36public 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 San Pedro";
                        Console.WriteLine(str);
                        string substr = str.Substring(23);
                        Console.WriteLine(substr);
                        Console.ReadKey() ;
                }
        }
}

當上面的代碼被編譯和執行時,它會產生下列結果:

Last night I dreamt of San Pedro
San Pedro

連接字串:

實例

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);
         Console.ReadKey() ;
      }
   }
}

當上面的代碼被編譯和執行時,它會產生下列結果:

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