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 小时前
07-02-源码-.NET Core GC分配路径
算法·unity·c#·.netcore·gc·1024程序员节
吴可可12311 小时前
C#调用摄像头拍照的三种API方案
c#
Msir_Modern16 小时前
Noita 元胞沙盒笔记
算法·unity·c#·游戏引擎·元胞自动机
星之擎18 小时前
Task 很优雅的取消方式是什么?C# 里面。
开发语言·c#
czhc114007566319 小时前
一周概念复盘:预热、漂移与门禁
c#
云中飞鸿20 小时前
.Net和C#有什么关系?(从C++视角观察)
开发语言·c#·.net
淡海水1 天前
07-04-源码-.NET Core GC清扫与压缩
unity·架构·c#·.netcore·gc·1024程序员节
zwm2698888151 天前
hd 3#负一西送风,能远程启不能远程停
c#
Ai-_Man1 天前
Meta Muse还是不可以导出左侧所有对话,只能点进去单条内容导出,方法不对吗?
开发语言·人工智能·ai·小程序·c#·1024程序员节
2401_885885042 天前
国际语音C#接口怎么写?.NET环境下实现国际语音验证码批量下发
开发语言·c#·.net