Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Positions of a Character in a String

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));
    }
}
like image 403
Rastin Radvar Avatar asked Oct 11 '13 09:10

Rastin Radvar


People also ask

How do I get the position of a character in a string in Python?

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.

What is position in a string?

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.

How do I find a specific character in a string in Java?

To locate a character in a string, use the indexOf() method.


1 Answers

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);
    }
}
like image 170
Étienne Miret Avatar answered Oct 26 '22 12:10

Étienne Miret