String オブジェクトが必要です:
String first = "/Some object that has a loop in it object/";
String second = "object";
私がする必要があるのは、2 番目のオブジェクトが最初のオブジェクトで何回繰り返されるかを見つけることです。その方法を教えてください。
バックグラウンドで正規表現を使用する次の 1 行を使用します。
String[] parts = first.split(second);
Stringは String 内で(parts.length - 1)回second
発生します。それで全部です。first
編集:
second
Stringに正規表現固有の文字が含まれている可能性がある場合に発生する可能性のある望ましくない結果を防ぐために、コメンテーターの1人が提案したように、メソッドPattern.quote(second)
に渡すときに使用できます。split()
最も簡単な方法はindexOf
、単語を見つけるたびに開始インデックスを進めて、ループで使用することです。
int ind = 0;
int cnt = 0;
while (true) {
int pos = first.indexOf(second, ind);
if (pos < 0) break;
cnt++;
ind = pos + 1; // Advance by second.length() to avoid self repetitions
}
System.out.println(cnt);
単語に自己反復が含まれている場合、これは単語を複数回検索します。このような「重複」検索を回避するには、上記のコメントを参照してください。
使用regex
例:
import java.util.regex.*;
class Test {
public static void main(String[] args) {
String hello = "HelloxxxHelloxxxHello"; //String you want to 'examine'
Pattern pattern = Pattern.compile("Hello"); //Pattern string you want to be matched
Matcher matcher = pattern.matcher(hello);
int count = 0;
while (matcher.find())
count++; //count any matched pattern
System.out.println(count); // prints how many pattern matched
}
}
ソース: Java 正規表現の一致数
String
2番目に分割してString
、結果の配列の長さを数えることができます。その出現回数よりも1つ多くの要素があります。Pattern
または、 andを使用することもできますMatcher
。これは、もう少し適切なアプローチです。
public static void main(String[] args) throws UnsupportedEncodingException, IOException {
String first = "/Some object that has a loop in it object/";
String second = "object";
System.out.println(first.split(Pattern.quote(second)).length - 1);
final Pattern pattern = Pattern.compile(Pattern.quote(second));
final Matcher matcher = pattern.matcher(first);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println(count);
}
いざという時のために忘れずに使いましょうPattern.quote
。
これを使って :
String first = "/Some object that has a loop in it object/";
String second = "object";
Pattern pattern = Pattern.compile(second);
Matcher matcher = pattern.matcher(first) ;
long count = 0;
while(matcher.find()) {
count ++;
}
System.out.println(count);
以下のようにしてみてください...
String str = "/Some object that has a loop in it object/";
String findStr = "object";
int lastIndex = 0;
int count =0;
while(lastIndex != -1){
lastIndex = str.indexOf(findStr,lastIndex);
if( lastIndex != -1){
count ++;
lastIndex+=findStr.length();
}
}
System.out.println(count);