💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 如何:使用字符串方法搜索字符串(C# 编程指南) [string](https://msdn.microsoft.com/zh-cn/library/362314fe.aspx) 类型(它是 [System.String](https://msdn.microsoft.com/zh-cn/library/system.string.aspx) 类的别名)为搜索字符串的内容提供了许多有用的方法。 下面的示例使用 [IndexOf](https://msdn.microsoft.com/zh-cn/library/system.string.indexof.aspx)、[LastIndexOf](https://msdn.microsoft.com/zh-cn/library/system.string.lastindexof.aspx)、[StartsWith](https://msdn.microsoft.com/zh-cn/library/system.string.startswith.aspx) 和 [EndsWith](https://msdn.microsoft.com/zh-cn/library/system.string.endswith.aspx) 方法搜素字符串。 ``` class StringSearch { static void Main() { string str = "Extension methods have all the capabilities of regular static methods."; // Write the string and include the quotation marks. System.Console.WriteLine("\"{0}\"", str); // Simple comparisons are always case sensitive! bool test1 = str.StartsWith("extension"); System.Console.WriteLine("Starts with \"extension\"? {0}", test1); // For user input and strings that will be displayed to the end user, // use the StringComparison parameter on methods that have it to specify how to match strings. bool test2 = str.StartsWith("extension", System.StringComparison.CurrentCultureIgnoreCase); System.Console.WriteLine("Starts with \"extension\"? {0} (ignoring case)", test2); bool test3 = str.EndsWith(".", System.StringComparison.CurrentCultureIgnoreCase); System.Console.WriteLine("Ends with '.'? {0}", test3); // This search returns the substring between two strings, so // the first index is moved to the character just after the first string. int first = str.IndexOf("methods") + "methods".Length; int last = str.LastIndexOf("methods"); string str2 = str.Substring(first, last - first); System.Console.WriteLine("Substring between \"methods\" and \"methods\": '{0}'", str2); // Keep the console window open in debug mode System.Console.WriteLine("Press any key to exit."); System.Console.ReadKey(); } } /* Output: "Extension methods have all the capabilities of regular static methods." Starts with "extension"? False Starts with "extension"? True (ignoring case) Ends with '.'? True Substring between "methods" and "methods": ' have all the capabilities of regular static ' Press any key to exit. */ ``` ## 请参阅 [C# 编程指南](https://msdn.microsoft.com/zh-cn/library/67ef8sbd.aspx) [字符串(C# 编程指南)](https://msdn.microsoft.com/zh-cn/library/ms228362.aspx) [如何:使用正则表达式搜索字符串(C# 编程指南)](https://msdn.microsoft.com/zh-cn/library/ms228595.aspx) [LINQ and Strings](https://msdn.microsoft.com/zh-cn/library/bb397915.aspx)