在C#中,处理字符串时可以使用许多不同的方法。
-
string.Concat: 用于连接两个或多个字符串。string result = string.Concat("Hello", " ", "World!"); -
string.Format: 用于格式化字符串,可以插入变量。string name = "Kimi"; string greeting = string.Format("Hello, {0}!", name); -
string.IsNullOrEmpty: 检查字符串是否为null或空。if (string.IsNullOrEmpty(input)) { /* ... */ } -
string.IsNullOrWhiteSpace: 检查字符串是否为null、空或仅包含空白字符。if (string.IsNullOrWhiteSpace(input)) { /* ... */ } -
string.Trim: 删除字符串开头和结尾的空白字符。string trimmed = input.Trim(); -
string.ToLower/string.ToUpper: 将字符串转换为全部小写或大写。string lower = input.ToLower(); string upper = input.ToUpper(); -
string.StartsWith/string.EndsWith: 检查字符串是否以指定的子字符串开始或结束。bool startsWithA = input.StartsWith("A"); bool endsWithExclamation = input.EndsWith("!"); -
string.Contains: 检查字符串是否包含指定的子字符串。bool containsHello = input.Contains("Hello"); -
string.IndexOf/string.LastIndexOf: 查找子字符串在字符串中的位置。int index = input.IndexOf("Hello"); int lastIndex = input.LastIndexOf("Hello"); -
string.Replace: 替换字符串中的字符或子字符串。string replaced = input.Replace("old", "new"); -
string.Split: 将字符串分割成子字符串数组。string[] parts = input.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); -
string.Join: 将对象数组连接成一个字符串,并用指定的分隔符分隔。string[] parts = { "Hello", "World" }; string joined = string.Join(" ", parts); -
string.Insert: 在字符串的指定位置插入字符串。string inserted = input.Insert(5, "Kimi"); -
string.Remove: 从字符串中移除子字符串。string removed = input.Remove(5, 4); -
string.Substring: 返回字符串的一个子字符串。string sub = input.Substring(5, 4); -
Regex类: 使用正则表达式处理字符串,如匹配、替换、拆分等。using System.Text.RegularExpressions; Regex regex = new Regex("pattern"); Match match = regex.Match(input);
这些方法覆盖了从简单的字符串连接到复杂的模式匹配等多种字符串处理场景。










