当前位置: 移动技术网 > IT编程>开发语言>.net > .net indexOf(String.indexOf 方法)

.net indexOf(String.indexOf 方法)

2017年12月12日  | 移动技术网IT编程  | 我要评论

平远中学,出版代理,袁姗姗再现西红柿蛋汤澡

返回 string 对象内第一次出现子字符串的字符位置。

public indexof(value:string, [startindex:number]) : number
搜索字符串,并返回在调用字符串内 startindex 位置上或之后找到的 value 的第一个匹配项的位置。此索引从零开始,这意味着字符串中的第一个字符被视为位于索引 0 而不是索引 1 处。如果未找到 value,该方法会返回 -1。

参数

value:string - 一个字符串;要搜索的子字符串。
startindex:number [可选] - 一个整数,指定搜索的开始索引。
返回
number - 指定子字符串的第一个匹配项的位置,或 -1。

indexof 方法
返回 string 对象内第一次出现子字符串的字符位置。
strobj.indexof(substring[, startindex])
参数
strobj
必选项。string 对象或文字。
substring
必选项。要在 string 对象中查找的子字符串。
starindex
可选项。该整数值指出在 string 对象内开始查找的索引。如果省略,则从字符串的开始处查找。
说明
indexof 方法返回一个整数值,指出 string 对象内子字符串的开始位置。如果没有找到子字符串,则返回 -1。
如果 startindex 是负数,则 startindex 被当作零。如果它比最大的字符位置索引还大,则它被当作最大的可能索引。
从左向右执行查找。否则,该方法与 lastindexof 相同。

示例

下面的示例说明了 indexof 方法的用法。
复制代码 代码如下:

function indexdemo(str2){
var str1 = "babebibobubabebibobu"
var s = str1.indexof(str2);
return(s);
}


实例:

我获得一个字符串a为 "1,18,33"
如果写成 a indexof("1") 好象查不出来 更重要的是 18和1前面都有个1所以成立的条件不准确 请问应该怎么写啊

indexof这样用

复制代码 代码如下:

string test = "1,18,33";
if (test.indexof("1") > -1)
{
response.write("存在");
}
else
{
response.write("不存在");
}

但是如果说只有1符合要求,而18中的1不符合要求,那不能用indexof来做,这样
复制代码 代码如下:

using system.text.regularexpressions;
string test = "1,18,33";
if (regex .ismatch(test, @"\b1\b"))
{
response.write("存在");
}
else
{
response.write("不存在");
}

注释:
\b 在正则中匹配一个单词边界
写了一个方法
复制代码 代码如下:

//src 源字符串
//tar 待比较字符串
private bool checkstring(string src, string tar)
{
string temp = regex.replace(tar, @"[.$^{\[(|)*+?\\]", "");
if (temp.length < tar.length)
return false;
if (regex.ismatch(src, @"\b" + tar + @"\b"))
return true;
return false;
}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网