ex
String str = "abc def ghi";
有没有类似 str.indexOf("abc")
返回1,str.indexOf("def")
返回2 的方法?
使用Java语言...
int getIndex(String str, String substring)
{
return Arrays.asList(str.split("\\s+")).indexOf(substring)+1;
}
免责声明:这并不是非常高效的方法。每次调用函数时,它会从头开始拆分整个字符串。
测试代码:
String str = "abc def ghi";
System.out.println(getIndex(str, "abc"));
System.out.println(getIndex(str, "def"));
输出:
1
2
解释:
str.split("\\s+")
通过空格分割字符串并将每个部分放入数组中。
Arrays.asList
返回一个数组的ArrayList
。
indexOf(substring)
在ArrayList
中查找字符串的位置。
+1
因为Java使用0索引,您需要1索引。
//Returns an array of integers with each string position
private int[] getStringPositions(String string, String subString){
String[] splitString = string.split(subString); //Split the string
int totalLen = 0; //Total length of the string, added in the loop
int[] indexValues = new int[splitString.length - 1]; //Instances of subString in string
//Loop through the splitString array to get each position
for (int i = 0; i < splitString.length - 1; i++){
if (i == 0) {
//Only add the first splitString length because subString is cut here.
totalLen = totalLen + splitString[i].length();
}
else{
//Add totalLen & splitString len and subStringLen
totalLen = totalLen + splitString[i].length() + subString.length();
}
indexValues[i] = totalLen; //Set indexValue at current i
}
return indexValues;
}
所以举个例子:
String string = "s an s an s an s"; //Length = 15
String subString = "an";
String[] parts = string.split(" ");
for(int i = 0; i < parts.length; i++)
{
if(parts[i].equals(parameter))
{
return i + 1;
}
}
由于您不是请求子字符串的索引,而是子字符串属于哪个单词位置,因此没有可用的内置方法。但是,您可以使用空格字符拆分输入字符串,并读取拆分方法返回的列表中的每个项目,并检查您的子字符串属于哪个列表项位置。
如果需要代码,请告诉我。