Find Positions of a Character in a String
61,411
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);
}
}
Author by
Rastin Radvar
Software Student in Shahid Rajaee University Of Lahijan :)
Updated on February 15, 2020Comments
-
Rastin Radvar about 4 years
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)); } }
-
Rastin Radvar over 10 yearsThank You So Much For Your Help , It's Work :) :X
-
Étienne Miret over 10 years@RastinRadvar When an answer works for you, you're supposed to accept it.
-
Rastin Radvar over 10 yearsThanks Dude ,It's Done . I'm New Here And don't know How To Work It Already . I'll Find out Everything soon , thanks again for helping :)
-
Rastin Radvar over 10 yearsThanks , It's Working Too but i didn't like to Use Arrays . I Found my answer but thanks a lot for helping :)