私は、与えられた文字列のインデックスを表示するメソッドを持っています。 Stringに指定された文字が含まれていない場合、結果は-1になります。 私のコードは次のようになります。このような状況で文字列内の文字の位置を出力する
public static int strpos(String text, char z) {
int x = 0;
char[] array = text.toCharArray();
for (int i = 0; i < array.length; i++) {
if (array[i] == z) {
x = i;
break;
} else {
x = -1;
}
}
return x;
}
public static void main(String[] args) {
System.out.println(strpos("abcdefghc", 'c'));
}
結果はある、と私はブレークを削除した場合、結果はです。どのように私は2と8の両方の結果を得るために私のコードをmodyfiできますか?
あなたは 'String.indexOf(文字)'メソッドを使用してみました? –