×

indexof的用法

C# 中IndexOf的用法问题?js indexof()函数用法

admin admin 发表于2022-05-31 15:30:34 浏览114 评论0

抢沙发发表评论

C# 中IndexOf的用法问题


C#中IndexOf的使用
IndexOf()
查找字串中指定字符或字串首次出现的位置,返首索引值,如:
str1.IndexOf(“字“); //查找“字”在str1中的索引值(位置)
str1.IndexOf(“字串“);//查找“字串”的第一个字符在str1中的索引值(位置)
str1.IndexOf(“字“,start,end);//从str1第start+1个字符起,查找end个字符,查找“字”在字符串STR1中的位置[从第一个字符算起]注意:start+end不能大于str1的长度

indexof参数为string,在字符串中寻找参数字符串第一次出现的位置并返回该位置。如string s=“0123dfdfdf“;int i=s.indexof(“df“);这时i==4。
如果需要更强大的字符串解析功能应该用Regex类,使用正则表达式对字符串进行匹配。

indexof() :在字符串中从前向后定位字符和字符串;所有的返回值都是指在字符串的绝对位置,如为空则为- 1
string test=“asdfjsdfjgkfasdsfsgfhgjgfjgdddd“;
test.indexof(’d’) =2 //从前向后 定位 d 第一次出现的位置
test.indexof(’d’,1) =2 //从前向后 定位 d 从第三个字符串 第一次出现的位置
test.indexof(’d’,5,2) =6 //从前向后 定位 d 从第5 位开始查,查2位,即 从第5位到第7位;
lastindexof() :在字符串中从后向前定位字符和字符串;、
用法和 indexof() 完全相同。

js indexof()函数用法


JavaScript中indexOf函数方法是返回String对象内第一次出现子字符串的字符位置。使用方法:

strObj.indexOf(subString[,  startIndex])
//其中strObj是必选项。String 对象或文字。
//subString是必选项。要在 String  对象中查找的子字符串。
//starIndex是可选项。该整数值指出在 String  对象内开始查找的索引。如果省略,则从字符串的开始处查找。

indexOf函数是从左向右执行查找。否则,该方法与 lastIndexOf
相同。下面的示例说明了indexOf函数方法的用法。

function IndexDemo(str2){
   var str1 =  “BABEBIBOBUBABEBIBOBU“
   var s = str1.indexOf(str2);
    return(s);
}

JavaScript中indexOf()函数方法返回一个整数值,指出  String 对象内子字符串的开始位置。如果没有找到子字符串,则返回 -1。如果 startindex 是负数,则 startindex  被当作零。如果它比最大的字符位置索引还大,则它被当作最大的可能索引。-indexof的用法


麻烦帮忙说说java中indexOf的用法,最好有事例,谢谢!


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

public static void main(String args) {
String str = “This is my original string!“;

str = str.substring(6); //str=str.substring(int beginIndex);截取掉str从首字母起长度为beginIndex的字符串,将剩余字符串赋值给str;
System.out.println(str);
str = str.substring(2,10); //截取str中从beginIndex开始至endIndex结束时的字符串,并将其赋值给str;
System.out.println(str);

String s = “This is my second original string!“;
String toDel = “original“;
if(s.startsWith(toDel))
s = s.substring(toDel.length());
else
if(s.endsWith(toDel))
s = s.substring(0,s.length() - toDel.length());
else
{
int index = s.indexOf(toDel); //IndexOf 方法 返回 String 对象内第一次出现子字符串的字符位置。
if(index != -1) {
String s1 = s.substring(0,index);
String s2 = s.substring(index+toDel.length());
s = s1 + s2;
}
else
System.out.println(“String: “+toDel+“ not be found!“);
}
System.out.println(s);

String sr = “This is my third string!“;
String sx= “is“;
int index = sr.indexOf(sx);
System.out.println(index);
int index2 = sr.indexOf(sx,3);
System.out.println(index2);
}
}
-indexof的用法