8.1.11 匹配和检索字符串(2)

来源:互联网 发布:淘宝千人千面怎么样 编辑:程序博客网 时间:2024/05/16 14:09

IndexOfAny()LastIndexOfAny()方法能够从字符串中查找与给定的字符数组中的匹配项的索引。其中,IndexOfAny()方法返回第一个匹配项的索引;LastIndexOfAny()方法返回最后一个匹配项的索引。它们的重载形式如下:

      public int IndexOfAny(char[] anyOf)

      public int IndexOfAny(char[] anyOf,int startIndex)

      public int IndexOfAny(char[] anyOf,int startIndex,int count)

      public int LastIndexOfAny(char[] anyOf)

      public int LastIndexOfAny(char[] anyOf,int startIndex)

      public int LastIndexOfAny(char[] anyOf,int startIndex,int count)

  其中,anyOf参数指定被比较的字符数组;startIndex参数指定字符位置开始;count参数指定比较的字符数量。

  下面的代码使用Contains()方法检查字符串变量initValue是否包含字符串“string”;使用StartsWith()方法检查字符串变量initValue是否以字符串“This”开头;使用IndexOf()方法查找字符串“is a s”在字符串变量initValue中的位置,如果找到,则返回第一个匹配项的开始索引,否则返回-1MatchString()函数首先使用了Response.Write()方法输出了字符串变量initValue的值,然后分别输出上述3个检查或查找操作的结果。

private string MatchString()

{

string initValue = "This is a string.";

Response.Write("源字符串:" + initValue + "<br />");

///检查是否包含

Response.Write("源字符串是否包含字符串/"string/""

+ initValue.Contains("string").ToString() + "<br />");

///检查开头

Response.Write("源字符串是否以字符串/"This/""

+ initValue.StartsWith("This").ToString() + "<br />");

///检索字符串

Response.Write("源字符串是否存在字符串/"is a s/""

+ (initValue.IndexOf("is a s") > -1 ? true : false).ToString()

+ "<br />");

return initValue;

}

原创粉丝点击