У меня есть строка, например
String value1 = "12345 abc 123 def 123";
и еще один, который нужно искать на нем
String value2 ="123";
например.
Как я могу вернуть все индексы, которые вторая строка появляется в первой? Из того, что я искал, indexOf
и lastIndexOf
ищет строку для первого и последнего индекса указанной строки.
Используйте необязательный параметр indexOf.
List<Integer> indexes = new ArrayList<>();
for (int idx = haystack.indexOf(needle);
idx != -1;
idx = haystack.indexOf(needle, idx + 1)) {
indexes.add(idx);
}
Использовать Regex лучше
class Test {
public static void main(String[] args) {
String value1= "12345 abc 123 def 123";
Pattern pattern = Pattern.compile("123");
Matcher matcher = pattern.matcher(value1);
int count = 0;
while (matcher.find()){
count++;
}
System.out.println(count);
}
}
Используйте indexOf(String str, int fromIndex))
в цикле.
Попробуйте регулярные выражения с Pattern
и Matcher
. Затем вы можете получить начальные индексы с помощью matcher.start()
, конечных индексов (эксклюзивных) с помощью matcher.end()
.
String value1 = "12345 abc 123 def 123";
String value2 = "123";
Pattern pattern = Pattern.compile(value2);
Matcher matcher = pattern.matcher(value1);
while (matcher.find()){
System.out.println("Start: " + matcher.start() + " -- End: " + matcher.end());
}
Это даст вам результат:
Start: 0 -- End: 3
Start: 10 -- End: 13
Start: 18 -- End: 21
Вам нужно будет реализовать эту функцию самостоятельно. Вы можете использовать что-то вроде:
package com.example.stringutils;
import java.util.ArrayList;
public class Util {
/** Return a list of all the indexes of the 'key' string that occur in the
* 'arbitrary' string. If there are none an empty list is returned.
*
* @param key
* @param arbitrary
* @return
*/
private static ArrayList<Integer> allIndexesOf(String key, String arbitrary) {
ArrayList<Integer> result = new ArrayList<Integer>();
if (key == null | key.length() == 0 | arbitrary == null | arbitrary.length()<key.length()) {
return result;
}
int loc = -1;
while ((loc = arbitrary.indexOf(key, loc+1)) > -1) {
result.add(loc);
}
return result;
}
}
Возможно, вам захочется увидеть, работают ли регулярные выражения быстрее (меньше строк кода не всегда быстрее, а просто "код").
12121
стога сена и121
иглы, регулярное выражение вернет только 1 совпадение, в то время как есть 2 перекрывающихся совпадения.