用于String中多个匹配的Java indexOf方法 [英] Java indexOf method for multiple matches in String
问题描述
我对indexOf方法有疑问。我想在字符串中找到多个X的情况。
I had a question about the indexOf method. I want to find multiple cases of "X" in a string.
假设我的字符串是x是x是x是x,我想在所有中找到x它的指数位置。
但是你如何针对多种情况这样做呢?这甚至可以用indexOf吗?
Suppose my string is "x is x is x is x", I want to find x in all of its index positions. But how do you do this for multiple cases? Is this even possible with indexOf?
我做了int temp = str.indexOf('x');
找到第一个x。我试着做一个for循环,其中我被初始化为字符串的长度,这不起作用,因为我一直在找到第一个x。
I did int temp = str.indexOf('x'); It find the first x. I tried to do a for loop where i is initialized to length of string and this did not work since I kept finding the first x over and over.
for (int y = temp1; y >= 0;y-- )
{
int temp = str.indexOf('x');
System.out.println(temp);
}
但这不起作用。我应该使用正则表达式吗?因为我真的不知道如何使用正则表达式方法。
But this does not work. Am I supposed to use regex? Because I don't really know how to use regex method.
任何帮助都将不胜感激,谢谢!
Any help would be appreciated, thanks!
推荐答案
indexOf
方法的第二个变体,它将start-index作为参数。
There is a second variant of the indexOf
method, which takes a start-index as a parameter.
i = str.indexOf('x');
while(i >= 0) {
System.out.println(i);
i = str.indexOf('x', i+1);
}
这篇关于用于String中多个匹配的Java indexOf方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!