-1

文字(「a」を調べるため)が見つかるたびにそれを出力し、次の文字に移動してチェックするプログラムを作成しようとしています。word.length の終わりまでそれを続けます。それは私がこれまでやってきたことですが、うまくいきません。

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Enter a word: ");
    String word = in.next();
    String a = "a";
    int i;
    char found = 0;
    char F;

    for (i = 0; i < word.length(); i++)
    {
        F = word.charAt(i);

        if (F == found)
        {
            System.out.println(i);
        }

    }


}
4

3 に答える 3

1

試してみてください

       Scanner in = new Scanner(System.in);
        System.out.print("Enter a word: ");
        String word = in.next();
        Pattern p=Pattern.compile("a");
        Matcher matcher=p.matcher(word);
        boolean b=false;
        while(b=matcher.find())
        {
            System.out.println(matcher.start()+"");
        }

編集:

Pattern.compile("a");

Compiles the given regular expression into a pattern

p.matcher(単語);

Creates a matcher that will match the given input against this pattern. 

aba式のすべての出現に対して、そのようにソース文字列を検索したい場合は、次のようにしaます

source:aba
index:012

式 a が 2 回出現していることがわかります。1 回目は位置 0 から始まり、2 回目は 2 から始まります。したがって、出力は次のようになります。0 2

于 2013-07-06T13:26:50.613 に答える
1

これを試して

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Enter a word: ");
    String word = in.next();        
    char F;

    for (int i = 0; i < word.length(); i++) {
        F = word.charAt(i);
        if (F == 'a') {
            System.out.println(i);
        }
    }
}
于 2013-07-06T13:37:57.607 に答える
0

これをシンプルに使う

 string.indexOf("a");
于 2013-07-06T13:16:44.277 に答える