0

I need to return unique value of character in string. I'm using String.indexOf(), but it doesn't work correct for me.

For example: camera

indexes: c-0, a-1, m-2, e-3, r-4, a-5

String.indexOf() always returns index 1 for letter "a", not 1 and 5 as I need.

Any ideas how to solve it?

user1950221
  • 13
  • 1
  • 7
  • 2
    The indexOf method has an overload which accepts a start index, so you can recursively call index of starting at the index of the last appearance of the character in question, until you find a complete list. https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(int,%20int) – Mark W Nov 21 '14 at 22:28
  • also check http://stackoverflow.com/questions/767759/occurrences-of-substring-in-a-string – zlinks Nov 21 '14 at 22:30

2 Answers2

0
public static void main(String[] args) {
    List<Integer> indexes = getIndexInString("camera", "a");
    System.out.println(indexes);

}

public static List<Integer> getIndexInString(String str, String charToFind) {
    List<Integer> indexes = new ArrayList<Integer>();

    int i = -1;

    while (true) {
        i = str.indexOf(charToFind, i + 1);
        if (i == -1)
            break;
        else
            indexes.add(i);
    }


    return indexes;
}
orak
  • 2,399
  • 7
  • 29
  • 55
0

Here you go.

public static void main(String[] args) {
    String text = "camera";
    String[] indexes = getIndexesOf(text);
    for(String i : indexes) {
        System.out.println(i);
    }
    System.out.println();
    int[] result = indexOfChar(text, "a");
    for(int i : result) {
        System.out.print(i +",");   
    }

}

public static String[] getIndexesOf(String text) {
    String[] indexes = new String[text.length()];
    for(int i=0; i<text.length(); i++) {
        indexes[i] = text.charAt(i) + "-" + i;
    }
    return indexes;
}

public static int[] indexOfChar(String text, String c) {
    List<Integer> indexOfChars = new ArrayList<Integer>();
    for(int i=0; i<text.length(); i++) {
        if(String.valueOf(text.charAt(i)).equals(c)) {
            indexOfChars.add(i);
        }
    }
    int [] retIndexes = new int[indexOfChars.size()];
    for(int i=0; i<retIndexes.length; i++) {
        retIndexes[i] = indexOfChars.get(i).intValue();
    }
    return retIndexes;
} 
javapadawan
  • 897
  • 6
  • 12
  • 29