Rastin Radvar Rastin Radvar - 4 months ago 10
Java Question

Find Positions of a Character in a String

How Can I Find a Character in 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 want code from java and I Write This and It's Not 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

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);
    }
}
Comments