Question

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));
    }
}
Était-ce utile?

La solution

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

Autres conseils

Start from the first character and iterate over all the characters till you reach the end. At each step test whether the character is a 'o'. If it is then print the position.

Here in Java:

    String s = "you are awesome honey";
    char[] array = s.toCharArray();
    for(int i = 0; i < array.length; i++){
        if(array[i] == 'o'){
            System.out.println(i);
        }   
    }
    static ArrayList<String> getCharPosition(String str, char mychar) {
            ArrayList<String> positions = new ArrayList<String>();

            if (str.length() == 0)
                return null;

            for (int i = 0; i < str.length(); i ++) {
                if (str.charAt(i) == mychar) {
                    positions.add(String.valueOf(i));
                }
            }

            return positions;
    }

String string = ("You are awesome honey");

ArrayList<String> result = getCharPosition(string, 'o');

for (int i = 0; i < result.size(); i ++) {
    System.out.println("char position is: " + result.get(i));
}

Output:

char position is: 1
char position is: 12
char position is: 17

Here is the function to find all positions of specific character in string

public ArrayList<Integer> findPositions(String string, char character) {
    ArrayList<Integer> positions = new ArrayList<>();
    for (int i = 0; i < string.length(); i++){
        if (string.charAt(i) == character) {
           positions.add(i);
        }
    }
    return positions;
}

And use it by

ArrayList<Integer> result = findPositions("You are awesome honey",'o'); 
// result will contains 1,12,17
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top