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));
}
}
Method 1: Get the position of a character in Python using rfind() Python String rfind() method returns the highest index of the substring if found in the given string. If not found then it returns -1.
A string position is a point within a string. It can be compared to an integer (which it is derived from), but it also acts as a pointer within a string so that the preceding and following text can be extracted.
To locate a character in a string, use the indexOf() method.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With