在 C# 中,字符串(string)是一个不可变对象,也就是说一旦字符串被创建后就不能被修改。以下是一些常用的字符串操作:
拼接字符串:使用 + 或 string.Concat 方法可以将多个字符串拼接在一起。
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName; // "John Doe"
string[] names = { "Alice", "Bob", "Charlie" };
string allNames = string.Concat(names); // "AliceBobCharlie"
字符串格式化:使用 string.Format 方法可以将格式化字符串与一个或多个对象拼接在一起,生成一个新的字符串。
string name = "John";
int age = 30;
string message = string.Format("My name is {0} and I'm {1} years old.", name, age); // "My name is John and I'm 30 years old."
字符串比较:使用 string.Equals 或 == 运算符可以比较两个字符串是否相等。
string str1 = "Hello";
string str2 = "hello";
bool isEqual = string.Equals(str1, str2, StringComparison.CurrentCultureIgnoreCase); // false
string str3 = "Hello";
string str4 = "Hello";
bool isEqual2 = str3 == str4; // true
字符串查找:使用 string.IndexOf 或 string.LastIndexOf 方法可以查找字符串中某个子串的位置。
string str = "The quick brown fox jumps over the lazy dog";
int index1 = str.IndexOf("fox"); // 16
int index2 = str.LastIndexOf("the"); // 31
字符串分割:使用 string.Split 方法可以将一个字符串按照指定的分隔符分割成多个子串。
string str = "Alice,Bob,Charlie";
string[] names = str.Split(','); // { "Alice", "Bob", "Charlie" }
字符串截取:使用 string.Substring 方法可以截取一个字符串的一部分。
string str = "Hello, World!";
string subStr = str.Substring(7, 5); // "World"
字符串替换:使用 string.Replace 方法可以将一个字符串中的某个子串替换成另一个字符串。
string str = "The quick brown fox jumps over the lazy dog";
string newStr = str.Replace("brown", "red"); // "The quick red fox jumps over the lazy dog"
这只是一些常用的字符串操作,实际上 C# 的字符串类提供了许多其他有用的方法,开发者可以根据具体需求选择合适的方法。