indexOfメソッドの使い方ですが、Microsoft から参照すると以下のようにありました。
strObj. indexOf(subString, startIndex)
strObj: String オブジェクトまたは文字列リテラル
subString:文字列から検索する部分文字列
startIndex:String オブジェクトの検索の開始位置を示すインデックス(省略した場合は先頭)
public static void main(String[] args) {
String word = "bgsbahb";
String key = "b";
System.out.println("count=" + search_count(word,key));
}
static int search_count(String word,String key) {
int count=0;
int result = word.indexOf(key);
while(result != -1) {
count++;
result = word.indexOf(key,++result);
}
return count;
}
また、indexOfを用いないプログラムを以下に載せておきます。
文字列”bgsbahb”から部分文字列”b”の個数をカウントしていくプログラムです。wordとkeyはプログラムで指定してありますが、scannerメソッドを用いれば入力のみでプログラムが実行できるようになります。
static int search_count(String word,String key) {
int count=0;
int i=0;
while( i + (key.length() - 1) < word.length()) {
String str1 = word.substring(i, i + key.length() );
if(str1.equals(key)) {
count++;
}
i++;
}
return count;
}
indexOfメソッドを使わず、equalsメソッドを使って先のプログラムを書き換えたものです。