Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert space before capital letter

Tags:

How to convert "HelloWorld" to "Hello World"? The splitting has to take place based on The upper-case letters, but should exclude the first letter.

like image 737
Emil Avatar asked Feb 03 '11 12:02

Emil


People also ask

How do you put a space before a capital letter in a string?

Use the replace() method to insert a space before the capital letters in a string, e.g. str. replace(/[A-Z]/g, ' $&'). trim() . The replace method will return a new string, where each capital letter is replaced by a space preceding the capital letter.


2 Answers

String output = input.replaceAll("(\\p{Ll})(\\p{Lu})","$1 $2"); 

This regex searches for a lowercase letter follwed by an uppercase letter and replaces them with the former, a space and the latter (effectively separating them with a space). It puts each of them in a capturing group () in order to be able to re-use the values in the replacement string via back references ($1 and $2).

To find upper- and lowercase letters it uses \p{Ll} and \p{Lu} (instead of [a-z] and [A-Z]), because it handles all upper- and lowercase letters in the Unicode standard and not just the ones in the ASCII range (this nice explanation of Unicode in regexes mostly applies to Java as well).

like image 125
Joachim Sauer Avatar answered Oct 19 '22 09:10

Joachim Sauer


Better is subjective. This takes some more lines of code:

public static String deCamelCasealize(String camelCasedString) {     if (camelCasedString == null || camelCasedString.isEmpty())         return camelCasedString;      StringBuilder result = new StringBuilder();     result.append(camelCasedString.charAt(0));     for (int i = 1; i < camelCasedString.length(); i++) {         if (Character.isUpperCase(camelCasedString.charAt(i)))         result.append(" ");         result.append(camelCasedString.charAt(i));     }     return result.toString(); } 

Hide this ugly implementation in a utility class and use it as an API (looks OK from the user perspective ;) )

like image 43
Andreas Dolk Avatar answered Oct 19 '22 09:10

Andreas Dolk