C# 字符串(String)
在 C# 中,您可以使用字符数组来表示字符串,但是,更常见的做法是使用 string 关键字来声明一个字符串变量。string 关键字是 System.String 类的别名。
创建 String 对象
您可以使用以下方法之一来穿件 string 对象:
- 通过给 String 变量指定一个字符串
- 通过使用 String 类构造函数
- 通过使用字符串串联运算符( + )
- 通过检索属性或调用一个返回字符串的方法
- 通过格式化方法来转换一个值或对象为它的字符串表示形式
结果:
String 类的属性
String 类有以下两个属性:
序号 | 属性名称 & 描述 |
1 | Chars |
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 ) |
7 | public static string Copy( string str ) |
8 | public void CopyTo( int sourceIndex, char[] destination, int destinationIndex, int count ) |
9 | public bool EndsWith( string value ) |
10 | public bool Equals( string value ) |
11 | public static bool Equals( string a, string b ) |
12 | public static string Format( string format, Object arg0 ) |
13 | public int IndexOf( char value ) |
14 | public int IndexOf( string value ) |
15 | public int IndexOf( char value, int startIndex ) |
16 | public int IndexOf( string value, int startIndex ) |
17 | public int IndexOfAny( char[] anyOf ) |
18 | public int IndexOfAny( char[] anyOf, int startIndex ) |
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 ) |
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 ) |
28 | public string Replace( string oldValue, string newValue ) |
29 | public string[] Split( params char[] separator ) |
30 | public string[] Split( char[] separator, int count ) |
31 | public bool StartsWith( string value ) |
32 | public char[] ToCharArray() |
33 | public char[] ToCharArray( int startIndex, int length ) |
34 | public string ToLower() |
35 | public string ToUpper() |
36 | public string Trim() |
比较字符串:
结果
连接字符串:
结果: