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);

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

相关推荐
唐青枫1 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech2 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf3 天前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m6253 天前
使用 C# 在 Excel 中应用多种字体样式
后端·c#
Artech3 天前
[MAF预定义的AIContextProvider-02]AgentSkillsProvider——将Agent Skills引入MAF
ai·c#·agent·agent skills·maf
2601_962072554 天前
李梦娇常识4600问|题库|打印版
sql·华为od·华为·c#·华为云·.net·harmonyos
m0_547486664 天前
《C#语言程序设计与实践》 全套PPT课件
c语言·c#·c语言程序设计
叶帆4 天前
【YFIOs】用C#开发硬件之设备上云
开发语言·unity·c#
IT方大同4 天前
(嵌入式操作系统)信号量
嵌入式硬件·c#
z落落4 天前
C# FileStream文件流读取文件
开发语言·c#