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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    cs 复制代码
    using System.Text.RegularExpressions;
    Regex regex = new Regex("pattern");
    Match match = regex.Match(input);

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

相关推荐
汤姆宝库9 小时前
BPE分词器的完整实现:字节对合并与词表构建
开发语言·人工智能·c#
Risehuxyc14 小时前
C# 发展历史
开发语言·c#
kyle~16 小时前
C# --- 反射
开发语言·c#
暴走约伯2 天前
【VFX工具链源码拆解 09】终极工业化闭环:基于 ID 规则驱动的全自动场景建档、骨骼挂载与男转女场景迁移
unity·c#·游戏引擎·材质
用户788477316343 天前
WinForms 迁移 WPF:Upgrade Assistant 覆盖 30%,剩下 70% 我手写了六周
c#
寂寞的船3 天前
【Unity知识速递】第13期 Unity 内存泄漏排查实战:从 Memory Profiler 到 Lua 引用泄漏的生产级全链路诊断
unity·junit·c#·游戏引擎·lua
用户3721574261353 天前
C# 提取 PDF 附件:包括文档附件和页面注释附件
c#
寂寞的船3 天前
【Unity Bug挑战】第12期 Awaitable 二次 await 死锁之谜 —— 为什么同一个异步操作等两次就卡死?
unity·c#·游戏引擎·bug
huaqianzkh5 天前
WinForm C#:循环修改控件UI闪烁卡顿?SuspendLayout / ResumeLayout 与 BeginUpdate 优化
开发语言·ui·c#
用户3721574261356 天前
C# 实现 Excel 单元格保护:锁定公式并允许编辑指定区域
c#·ai编程·编程语言