C#中字符串的一些常用方法详解

  1. Length - 返回字符串的长度。

    string str = "Hello"; int length = str.Length; // length = 5

  2. Substring(int startIndex) - 返回从指定索引开始的子字符串。

    string str = "Hello World"; string sub = str.Substring(6); // sub = "World"

  3. Substring(int startIndex, int length) - 返回从指定索引开始,长度为指定值的子字符串。

    string str = "Hello World"; string sub = str.Substring(6, 5); // sub = "World"

  4. IndexOf(string value) - 返回子字符串在字符串中首次出现的索引。

    string str = "Hello World"; int index = str.IndexOf("World"); // index = 6

  5. LastIndexOf(string value) - 返回子字符串在字符串中最后一次出现的索引。

    string str = "Hello World"; int lastIndex = str.LastIndexOf("l"); // lastIndex = 9

  6. ToUpper() - 将字符串转换为大写。

    string str = "Hello World"; string upper = str.ToUpper(); // upper = "HELLO WORLD"

  7. ToLower() - 将字符串转换为小写。

    string str = "Hello World"; string lower = str.ToLower(); // lower = "hello world"

  8. Trim() - 移除字符串开头和结尾的空白字符。

    string str = " Hello World "; string trimmed = str.Trim(); // trimmed = "Hello World"

  9. Replace(string oldValue, string newValue) - 替换字符串中的字符或子字符串。

    string str = "Hello World"; string replaced = str.Replace("World", "C#"); // replaced = "Hello C#"

  10. Split(params char[] separator) - 将字符串分割成子字符串数组。

    string str = "Hello,World,C#"; string[] parts = str.Split(','); // parts = ["Hello", "World", "C#"]

  11. Contains(string value) - 检查字符串是否包含指定的子字符串。

    string str = "Hello World"; bool contains = str.Contains("World"); // contains = true

  12. StartsWith(string value) - 检查字符串是否以指定的子字符串开始。

    string str = "Hello World"; bool startsWith = str.StartsWith("Hello"); // startsWith = true

  13. EndsWith(string value) - 检查字符串是否以指定的子字符串结束。

    string str = "Hello World"; bool endsWith = str.EndsWith("World"); // endsWith = true

  14. Concat(string str0, string str1, ...) - 连接多个字符串。

    string str1 = "Hello"; string str2 = "World"; string concat = string.Concat(str1, " ", str2); // concat = "Hello World"

  15. Format(IFormatProvider provider, string format, object[] args) - 格式化字符串。

    string name = "World"; string formatted = string.Format("Hello, {0}!", name); // formatted = "Hello, World!"

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值