我想这样查找,有字符串hello world llo,然后我要查找llo的位置是在哪里,这时我想返回的是12,而不是2,请问怎样写代码?
有人说indexOf(String str)+indexOf(String str,int i)可以解决这个问题``我不知道indexOf(String str,int i)有什么不同的地方``希望各位的回答不要了了几句带过`谢谢`
有人说indexOf(String str)+indexOf(String str,int i)可以解决这个问题``我不知道indexOf(String str,int i)有什么不同的地方``希望各位的回答不要了了几句带过`谢谢`
Returns the index within this string of the first occurrence of the specified substring
2 public int indexOf(String str,int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
看一下第二个的参数名就知道是什么意思了 !
=========================
从第I个位置开始找,大于2就找到会是12了。
* @param pattern 查找的字符
* @param str 输入字符串
* @times 第几次出现
* @return -1 没有满足的字符 〉0 出现的地方
public static int matchIndex(String pattern, String str, int times) {
int index = 0;
while(times-- > 0) {
index = str.indexOf(pattern,i);
index += pattern.length();
}
return index;
}
返回12
public static int matchIndex(String pattern, String str, int times) {
int i = 0;
while(times-- > 0) {
i = str.indexOf(pattern,i);
if(times != 0)
i += pattern.length();
}
return i;
}
import java.util.*;
public class TestToDel {
public static void main(String[] args) {
String s = "hello world llo";
int sum=0;
String[] a = s.split(" ");
for(int i=0;i<a.length;i++){
if(a[i].equals("llo")){
for(int j=i-1;j>=0;j--){
sum +=a[j].length();
}
System.out.println(sum+i);
}
}
}
}
----------------------------
String str = "hello world llo";
Pattern p = Pattern.compile("\\bllo\\b");
Matcher m = p.matcher(str);
while (m.find()){
System.out.println(m.start());
}
System.out.println(str.indexOf(" llo ")+1);
* @param pattern 查找的字符
* @param str 输入字符串
* @times 第几次出现
* @return -1 没有满足的字符 〉0 出现的地方
public static int matchIndex(String pattern, String str, int times) {
int i = 0;
while(times-- > 0) {
i = str.indexOf(pattern,i);
if(times != 0)
i += pattern.length();
}
return i;
}我的代码可以查找任意的阿,你看看参数的意思,老大~~
System.out.println("hello world llo".lastIndexOf("llo"));