Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong indexOf in String Array

I want to sort a String array by second char, but index of char at position "1" is always -1 and so sort does not working. What is wrong?

String[] wordList = outString.toString().split(", ");

for (int i = 0; i < wordList.length; i++) {
    int n =wordList[i].indexOf(wordList.toString().charAt(1));
}

Arrays.sort(wordList, 1,0);

for (String str : wordList) {
    System.out.println(str);
}
like image 570
Anton A. Avatar asked Dec 16 '22 12:12

Anton A.


1 Answers

This wordList.toString().charAt(1) gives you the toString() representation of a String[], which is probably not what you want.

String [] test = new String [] {"a","b","c"};
System.out.println(test.toString());

Output

[Ljava.lang.String;@23fc4bec

You should find sorting by the second index easier if you use a custom Comparator and allow Collections.sort() to sort your wordList (after putting it into a List first).

Also note that your split contains a whitespace which can lead to some more confusion split(", ");.

like image 149
Deepak Bala Avatar answered Dec 31 '22 06:12

Deepak Bala