0

文字列(「恐竜」)を持っていて、その方法は正確にはわかりませんが、文字「o」の位置を取得するにはどうすればよいですか。文字列が(」のように、2つの位置を取得することは可能ですか。プール」)

4

6 に答える 6

3

最初の質問については、String#indexOf(int)を使用して、文字列内のすべての「o」のインデックスを取得できます。

int oPos = yourString.indexOf('o');

2番目の質問については、 String.indexOf(int、int)を使用するメソッドを作成し、文字列の検索された部分を繰り返さないように前のインデックスを追跡することで、特定の文字のすべての位置を取得できます。位置を配列またはリストに格納できます。

于 2012-08-27T00:06:08.400 に答える
1

indexOfループで使用:

String s = "Pool";
int idx = s.indexOf('o');
while (idx > -1) {
  System.out.println(idx);
  idx = s.indexOf('o', idx + 1);
}
于 2012-08-27T00:14:26.440 に答える
0

これを試して

 String s= "aloooha";
 char array[] = s.toCharArray();
 Stack stack = new Stack();

 for (int i = 0; i < array.length; i++) {
    if(array[i] == 'o'){
      stack.push(i);
    }
 }        
 for (int i = 0; i < stack.size(); i++) {
    System.out.println(stack.get(i));
 }
于 2012-08-27T05:53:35.573 に答える
0

これはおそらく少し船外に進んでいますが、ちょっと;)

String master = "Pool";
String find = "o";

Pattern pattern = Pattern.compile(find);
Matcher matcher = pattern.matcher(master);

String match = null;

List<Integer[]> lstMatches = new ArrayList<Integer[]>(5);
while (matcher.find()) {

    int startIndex = matcher.start();
    int endIndex = matcher.end();

    lstMatches.add(new Integer[] {startIndex, endIndex});

}

for (Integer[] indicies : lstMatches) {

    System.out.println("Found " + find + " @ " + indicies[0]);

}

私に与えます

Found o @ 1
Found o @ 2

素晴らしいことは、「oo」も見つけることができるということです

于 2012-08-27T00:21:47.383 に答える
0

String を char 配列に変換しようとしましたか?

int counter = 0;
String input = "Pool";
for(char ch : input.toCharArray()) {
    if(ch == 'o') {
        System.out.println(counter);
    }
    counter += 1;
}
于 2012-08-27T01:00:37.477 に答える
0

単に:

public static int[] getPositions(String word, char letter)
{
    List<Integer> positions = new ArrayList<Integer>();
    for(int i = 0; i < word.length(); i++) if(word.charAt(i) == letter) positions.add(i);

    int[] result = new int[positions.size()];
    for(int i = 0; i < positions.size(); i++) result[i] = positions.get(i);

    return result;
}
于 2012-08-27T00:21:00.980 に答える