自学内容网 自学内容网

C# string字符串常用处理方法

在C#中,处理字符串时可以使用许多不同的方法。

  1. string.Concat: 用于连接两个或多个字符串。

    string result = string.Concat("Hello", " ", "World!");
  2. string.Format: 用于格式化字符串,可以插入变量。

    string name = "Kimi";
    string greeting = string.Format("Hello, {0}!", name);
  3. string.IsNullOrEmpty: 检查字符串是否为null或空。

    if (string.IsNullOrEmpty(input)) { /* ... */ }
  4. string.IsNullOrWhiteSpace: 检查字符串是否为null、空或仅包含空白字符。

    if (string.IsNullOrWhiteSpace(input)) { /* ... */ }
  5. string.Trim: 删除字符串开头和结尾的空白字符。

    string trimmed = input.Trim();
  6. string.ToLower / string.ToUpper: 将字符串转换为全部小写或大写。

    string lower = input.ToLower();
    string upper = input.ToUpper();
  7. string.StartsWith / string.EndsWith: 检查字符串是否以指定的子字符串开始或结束。

    bool startsWithA = input.StartsWith("A");
    bool endsWithExclamation = input.EndsWith("!");
  8. string.Contains: 检查字符串是否包含指定的子字符串。

    bool containsHello = input.Contains("Hello");
  9. string.IndexOf / string.LastIndexOf: 查找子字符串在字符串中的位置。

    int index = input.IndexOf("Hello");
    int lastIndex = input.LastIndexOf("Hello");
  10. string.Replace: 替换字符串中的字符或子字符串。

    string replaced = input.Replace("old", "new");
  11. string.Split: 将字符串分割成子字符串数组。

    string[] parts = input.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  12. string.Join: 将对象数组连接成一个字符串,并用指定的分隔符分隔。

    string[] parts = { "Hello", "World" };
    string joined = string.Join(" ", parts);
  13. string.Insert: 在字符串的指定位置插入字符串。

    string inserted = input.Insert(5, "Kimi");
  14. string.Remove: 从字符串中移除子字符串。

    string removed = input.Remove(5, 4);
  15. string.Substring: 返回字符串的一个子字符串。

    string sub = input.Substring(5, 4);
  16. Regex: 使用正则表达式处理字符串,如匹配、替换、拆分等。

    using System.Text.RegularExpressions;
    Regex regex = new Regex("pattern");
    Match match = regex.Match(input);

这些方法覆盖了从简单的字符串连接到复杂的模式匹配等多种字符串处理场景。


原文地址:https://blog.csdn.net/2302_77639120/article/details/142794880

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!