在字符串中查找子字符串的位置(而不是indexOf)

3

ex

String str = "abc def ghi";

有没有类似 str.indexOf("abc") 返回1,str.indexOf("def") 返回2 的方法?

使用Java语言...

4个回答

7
这样怎么样?
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索引。


也许将您的代码扩展一下会使其更易读,但对于这个问题,+1 对您已经足够了。 - Marc
@Marc 看起来把它变长好像有点浪费。我希望添加的解释足以使其可读。 - Bernhard Barker

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";

答案将返回 indexValues = (2, 7, 12)。

1
我认为没有这个的本地功能。但是你可以自己编写。
看起来你想根据空格字符拆分字符串。
String[] parts = string.split(" ");

循环遍历创建的数组,并返回索引+1(因为Java使用零作为数组起始索引)。
for(int i = 0; i < parts.length; i++)
{
  if(parts[i].equals(parameter))
  {
     return i + 1;
  }
}

1

由于您不是请求子字符串的索引,而是子字符串属于哪个单词位置,因此没有可用的内置方法。但是,您可以使用空格字符拆分输入字符串,并读取拆分方法返回的列表中的每个项目,并检查您的子字符串属于哪个列表项位置。

如果需要代码,请告诉我。


1
很好的解释,但你必须在你的回答中展示代码,否则这只是一篇长评论。 - CodingIntrigue
感谢RGraham的宝贵反馈。我会确保今后做到这一点。 - MansoorShaikh
1
@RGraham 确实,代码通常有助于更好地解释。但我不同意总是需要在答案中添加代码。为 OP 提供指南也是一个很好的答案。 - Yu Hao

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接