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

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

相关推荐
cjp5602 小时前
001.Blazor简介
c#
工程师0073 小时前
C# 程序集、IL、CLR 执行流程
c#·clr·il·程序集
xxjj998a3 小时前
PHP vs C#:核心差异全解析
开发语言·c#·php
我不在你不在4 小时前
C# 异步与LINQ实战亮点
c#
游乐码4 小时前
c#预处理器指令
c#
之歆5 小时前
DAY13_CSS3进阶完全指南 —— 背景、边框、文本、渐变、滤镜与 Web 字体(上)
前端·c#·css3
工程师00714 小时前
C# 装箱、拆箱 底层原理
c#·装箱和拆箱
清风明月一壶酒15 小时前
OpenClaw自动处理Word文档全流程
开发语言·c#·word
工程师00717 小时前
C# 值类型 / 引用类型 内存布局(栈、堆、托管堆)
c#·值类型与引用类型
chao18984420 小时前
完整MES系统实现 (C# 客户端服务器)
服务器·windows·c#