如何:使用字符串方法搜索字符串(C# 编程指南)
string 类型(它是 System.String 类的别名)为搜索字符串的内容提供了许多有用的方法。下面的示例使用 IndexOf、LastIndexOf、StartsWith 和 EndsWith 方法。
示例
class StringSearch
{
static void Main()
{
string str = "A silly sentence used for silly purposes.";
System.Console.WriteLine("'{0}'",str);
bool test1 = str.StartsWith("a silly");
System.Console.WriteLine("starts with 'a silly'? {0}", test1);
bool test2 = str.StartsWith("a silly", System.StringComparison.OrdinalIgnoreCase);
System.Console.WriteLine("starts with 'a silly'? {0} (ignoring case)", test2);
bool test3 = str.EndsWith(".");
System.Console.WriteLine("ends with '.'? {0}", test3);
int first = str.IndexOf("silly");
int last = str.LastIndexOf("silly");
string str2 = str.Substring(first, last - first);
System.Console.WriteLine("between two 'silly' words: '{0}'", str2);
}
}
输出
'A silly sentence used for silly purposes.' starts with 'a silly'? False starts with 'a silly'? True (ignore case) ends with '.'? True between two 'silly' words: 'silly sentence used for '