Java的indexOf方法用于字符串中的多个匹配
我有一个关于 indexOf 方法的问题。我想在字符串中查找多个“X”的情况。
假设我的字符串是“x is x is x is x”,我想在它的所有索引位置找到x。 但对于多种情况,如何做到这一点呢?这对于indexOf 来说是可能的吗?
我做了 int temp = str.indexOf('x'); 它找到第一个x。我尝试做一个 for 循环,其中 i 被初始化为字符串的长度,但这不起作用,因为我一遍又一遍地寻找第一个 x 。
for (int y = temp1; y >= 0;y-- )
{
int temp = str.indexOf('x');
System.out.println(temp);
}
但这是行不通的。我应该使用正则表达式吗?因为我真的不知道如何使用正则表达式方法。
任何帮助将不胜感激,谢谢!
I had a question about the indexOf method. I want to find multiple cases of "X" in a string.
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?
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
indexOf
方法还有第二种变体,它采用起始索引作为参数。There is a second variant of the
indexOf
method, which takes a start-index as a parameter.indexOf
方法还有另一个版本,以fromIndex
作为参数。因此,您可以循环调用它,每次传递
prevPosition + 1
作为第二个参数。文档:
http:// download.oracle.com/javase/6/docs/api/java/lang/String.html#indexOf(int, int)
There's a another version of
indexOf
method, takingfromIndex
as parameter.So, you can call it in a loop, each time passing
prevPosition + 1
as a second parameter.Documentation:
http://download.oracle.com/javase/6/docs/api/java/lang/String.html#indexOf(int, int)
您可以使用 indexOf。因此,在循环中存储“x”的最后一个位置,然后使用该索引 + 1 再次搜索。
You can specify the start index with indexOf. So, in your loop you store the last position of 'x', then search again using that index + 1.
这是 Streams API 的解决方案:
输出将如下所示:
如果您想在结果中添加大写字母,则需要更改
filter
的参数闭包:然后输出将是像这样:
此外,如果您只想使用结果或打印出来以进行快速测试,您可以使用
forEach
终端操作来完成:Here is the solution with Streams API :
Output will be like this :
If you want to add upper case letters into your result, you need to change the
filter
's argument closure with :Then the output will be like this :
Additionally if you just want to use the results or print it out for quick testing purposes you can do it with using
forEach
terminal operation: