c#常用对字符串操作的函数

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# 中一些常用的字符串函数,还有很多其他的字符串函数可以使用。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值