C# - 字符串

在 C# 中,你可以将字符串用作字符数组。然而,更常见的做法是使用 string 关键字来声明字符串变量。 string 关键字是 System.String 类的别名。

创建字符串对象

您可以使用以下方法之一创建字符串对象 -

  • 通过将字符串文字赋值给字符串变量

  • 通过使用字符串类构造函数

  • 通过使用字符串连接运算符 (+)

  • 通过检索属性或调用返回字符串的方法

  • 通过调用格式化方法将值或对象转换为其字符串表示形式

以下示例演示了这一点 -

using System;
namespace StringApplication {
   class Program {
      static void Main(string[] args) {
         //来自字符串文字和字符串连接
         string fname, lname;
         fname = "Rowan";
         lname = "Atkinson";

         char[] letters = {'H', 'e', 'l', 'l', 'o'};
         string[] sarray = {
            "Hello",
            "From",
            "Tutorials",
            "Point"
         };

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

        //通过使用字符串构造函数 { 'H', 'e', 'l', 'l','o' };
         string greetings = new string(letters);
         Console.WriteLine("Greetings: {0}", greetings);

         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);
      }
   }
}

当编译并执行上述代码时,它会产生以下结果 -

Full Name: RowanAtkinson
Greetings: Hello
Message: Hello From Tutorials 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 Clone()

返回此字符串实例的引用。

2 CompareOrdinal()

通过计算字符串中对应字符的数值来比较两个字符串。

3 Compare()

比较使用指定规则(区分大小写、特定于文化等)连接两个指定的字符串对象。

4 Concat()

连接两个字符串对象。

5 Contains()

返回一个值,指示指定的字符串对象是否出现在此字符串中。

6 CopyTo()

将指定数量的字符从此字符串复制到字符数组中的指定位置。

7 EndsWith()

判断此字符串实例的末尾是否与指定字符串匹配。

8 Equals()

判断两个指定的 String 对象是否具有相同的值。

9 Format()

它将字符串中的格式项替换为相应对象的字符串表示形式。

10 GetEnumerator()

它检索一个可以遍历此字符串中各个字符的枚举器。

11 GetHashCode()

它返回此字符串的哈希码字符串。

12 IndexOfAny()

它在指定的字符数组中查找任意字符首次出现的索引。

13 IndexOf()

它返回此字符串中指定子字符串首次出现的从零开始的索引。

14 Insert()

在当前字符串的指定索引处插入一个字符串。

15 IsNullOrEmpty()

检查字符串是否为 null 或空。

16 IsNullOrWhiteSpace()

检查字符串是否为 null、空或仅包含空格。

17 Join()

使用指定的分隔符连接对象数组的字符串表示形式。

18 LastIndexOf()

返回字符串中指定子字符串最后一次出现的索引(从零开始)。

19 PadLeft()

使用指定字符填充字符串左侧,以达到给定的总长度。

20 PadRight()

使用指定字符填充字符串右侧,以达到给定的总长度。

21 Remove()

从当前字符串的指定位置开始,删除指定数量的字符。

22 Replace()

将所有出现的指定子字符串替换为另一个子字符串。

23 Split()

根据指定的分隔符将字符串拆分为多个子字符串。

24 StartWith()

判断此字符串实例的开头是否与指定字符串匹配。

25 Substring()

从指定索引处开始检索子字符串,直到字符串末尾。

26 ToCharArray()

转换将字符串转换为字符数组。

27 ToLower()

将字符串的所有字符转换为小写。

28 ToString()

返回对象的字符串表示形式。

29 ToUpper()

将字符串的所有字符转换为大写。

30 TrimEnd()

从当前字符串中删除所有尾随空格。

31 TrimStart()

从当前字符串中删除所有前导空格。

32 Trim()

该函数用于从当前字符串中删除所有前导和尾随空格。

本章总结了 C# 编程中常用的字符串类的关键方法。完整的方法列表和字符串类的构造函数,请访问 MSDN 库。

示例

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

比较字符串

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);
      }
   }
}

当编译并执行上述代码时,它会产生以下结果 -

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("", 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