Priyanshu Priyanshu - 21 days ago 5
Java Question

How can String transformed to only lower case

Arrange string in alphabetical order. I want the string transformed so that uppercase letters are converted to lowercase and other characters are removed the result shouild be sorted ascending.

public static void main(String[] args) {
String text = "She sells sea shells";
String p1 = "aeeeehhllllssssss"; // desired result

char[] charArray = text.toCharArray();
Arrays.sort(charArray);
String sortedString = new String(charArray);
System.out.println( sortedString.equals( p1 ));
}

Answer

Replace the line

char[] charArray = text.toCharArray();

by

char[] charArray = text.toLowerCase().replaceAll( "[^\\p{Lower}]","" ).toCharArray();

This uses a regular expression:

Runnable example:

https://ideone.com/WSvUZy