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