javaarrayssorting

How to find highest alphabet in a String?


Consider the example "DBCZAQW" I have to find the charcter which is greatest among other characters in the string(Z in this case) I have sorted the arrays in ths manner

 String s="DBCZAQW";
 char arr[]=s.toCharArray();
 Arrays.sort(arr);
 System.out.println(arr[s.length()-1]);

Is there any procedure to find the character other than sorting????


Solution

  • You can iterate through all characters in the string

    char result = s.charAt(0);
    for(int i = 1; i < s.length(); i++)
        result = result > s.charAt(i) ? result : s.charAt(i);
    System.out.println(result);
    

    Note: be careful with empty string :)