Find Positions of a Character in a String

Rastin Radvar picture Rastin Radvar · Oct 11, 2013 · Viewed 59.3k times · Source

How can I find a character in a String and print the position of character all over the string? For example, I want to find positions of 'o' in this string : "you are awesome honey" and get the answer = 1 12 17.

I wrote this, but it doesn't work :

public class Pos {
    public static void main(String args[]){
        String string = ("You are awesome honey");
        for (int i = 0 ; i<string.length() ; i++)
        if (string.charAt(i) == 'o')
        System.out.println(string.indexOf(i));
    }
}

Answer

Etienne Miret picture Etienne Miret · Oct 11, 2013

You were almost right. The issue is your last line. You should print i instead of string.indexOf(i):

public class Pos{
    public static void main(String args[]){
        String string = ("You are awesome honey");
        for (int i = 0 ; i<string.length() ; i++)
        if (string.charAt(i) == 'o')
        System.out.println(i);
    }
}