字符串是开发中最常用的类型,C# 提供了丰富的操作方法,如截取、替换、拼接、判断等。
案例:字符串工具类
public class StringHelper { // 拼接字符串(比+号高效) public static string JoinStrings(params string[] parts) { return string.Join("-", parts); } // 截取字符串 public static string Substring(string str, int startIndex, int length) { if (string.IsNullOrEmpty(str)) return ""; return str.Substring(startIndex, Math.Min(length, str.Length - startIndex)); } // 替换字符串 public static string ReplaceKeyword(string str, string keyword, string replacement) { return str.Replace(keyword, replacement); } // 判断字符串是否包含关键词 public static bool ContainsKeyword(string str, string keyword) { return !string.IsNullOrEmpty(str) && str.Contains(keyword); } } // 调用示例 string joined = StringHelper.JoinStrings("2024", "01", "08"); Console.WriteLine("拼接结果:" + joined); // 输出:2024-01-08 string sub = StringHelper.Substring("C#编程教程", 2, 3); Console.WriteLine("截取结果:" + sub); // 输出:编程教 string replaced = StringHelper.ReplaceKeyword("C#很难", "难", "简单"); Console.WriteLine("替换结果:" + replaced); // 输出:C#很简单 bool hasCSharp = StringHelper.ContainsKeyword("学习C#", "C#"); Console.WriteLine("是否包含C#:" + hasCSharp); // 输出:True