c#常用对字符串操作的函数
C# 提供了许多用于操作字符串的内置函数,下面列举一些常用的字符串函数和相应的代码示例:
string.Length
:返回字符串中字符的数量。
string str = "Hello, World!";
int len = str.Length;
Console.WriteLine(len); // 输出 13
string.Substring(int startIndex, int length)
:从指定的位置开始,提取指定长度的子字符串。
string str = "Hello, World!";
string sub = str.Substring(0, 5); // 从 0 开始,提取 5 个字符
Console.WriteLine(sub); // 输出 "Hello"
string.Trim()
:删除字符串开头和结尾的空格。
string str = " Hello, World! ";
string trimmedStr = str.Trim();
Console.WriteLine(trimmedStr); // 输出 "Hello, World!"
string.Replace(string oldValue, string newValue)
:将字符串中所有的旧值替换为新值。
string str = "Hello, World!";
string newStr = str.Replace("World", "C#");
Console.WriteLine(newStr); // 输出 "Hello, C#!"
string.IndexOf(string value)
:在字符串中查找指定的字符串,并返回其第一次出现的位置。如果未找到,则返回 -1。
string str = "Hello, World!";
int index = str.IndexOf("World");
Console.WriteLine(index); // 输出 7
string.ToUpper()
和 string.ToLower()
:将字符串分别转换为大写或小写字母。
string str = "Hello, World!";
string upper = str.ToUpper();
string lower = str.ToLower();
Console.WriteLine(upper); // 输出 "HELLO, WORLD!"
Console.WriteLine(lower); // 输出 "hello, world!"
string.Split(char[] separator)
:根据指定的分隔符将字符串拆分为多个子字符串。
string str = "apple,banana,orange";
string[] arr = str.Split(',');
foreach (string s in arr)
{
Console.WriteLine(s);
}
// 输出:
// apple
// banana
// orange
string.IsNullOrEmpty(string value)
:判断字符串是否为空或 null。
string str1 = null;
string str2 = "";
string str3 = "Hello";
bool result1 = string.IsNullOrEmpty(str1); // true
bool result2 = string.IsNullOrEmpty(str2); // true
bool result3 = string.IsNullOrEmpty(str3); // false
string.Join(string separator, IEnumerable<string> values)
:将多个字符串按指定分隔符连接起来。
string[] arr = {"apple", "banana", "orange"};
string str = string.Join(",", arr);
Console.WriteLine(str); // 输出 "apple,banana,orange"
string.Format(string format, object arg0, object arg1, object arg2, ...)
:将多个对象格式化为字符串。
csharpCopy codestring str = string.Format("My name is {0}, I am {1} years old.", "Tom", 18);
Console.WriteLine(str); // 输出 "My name is Tom, I am 18 years old."
string.Contains(string value)
:判断字符串是否包含指定的子字符串。
string str = "Hello, World!";
bool result1 = str.Contains("World"); // true
bool result2 = str.Contains("C#"); // false
string.Compare(string strA, string strB)
:比较两个字符串的大小关系,返回一个整数值。
string str1 = "abc";
string str2 = "def";
int result1 = string.Compare(str1, str2); // 返回一个小于 0 的值
int result2 = string.Compare(str2, str1); // 返回一个大于 0 的值
int result3 = string.Compare(str1, str1); // 返回 0
上述是 C# 中一些常用的字符串函数,还有很多其他的字符串函数可以使用。