2

I need to write a program where the user enters an object string like "HelloIamYourNeighbor" and returns "Hello I am your neighbors"

so far I have been able to convert the uppercase to lowers case but I am having trouble inserting the spaces between the capital letters.

for (int i = 0; i < input.length(); i++) {
    if (input.contains("(?=\\p{Lu})")) {
        str.append(" ");
    }
    if (Character.isUpperCase(input.charAt(i)) && i != 0) {
        str.setCharAt(i, Character.toLowerCase(input.charAt(i)));
}
}
System.out.println(str);    
Mansukh Singh
  • 31
  • 1
  • 4
  • This may be of help http://stackoverflow.com/questions/4886091/insert-space-after-capital-letter?rq=1 – Tim Feb 27 '14 at 22:04

3 Answers3

4

One-liner:

string.replaceAll("([A-Z])", " $1");

() - this is capture group, which matches CAPITAL LETTERS and it replaces this match with white space and this matched letter.

bartektartanus
  • 15,284
  • 6
  • 74
  • 102
3

I would do this:

StringBuilder sb = new StringBuilder();
for(int i=0; i<string.length(); i++) {
    char c = string.charAt(c);
    if(Character.isUpperCase(c)){
        sb.append(' ');
    }
    sb.append(c);
}
String newString = sb.toString();
PlasmaPower
  • 1,864
  • 15
  • 18
1

Assuming "str" is a StringBuilder or StringBuffer, you want to remove the "input.contains" check and str.append there. You also want to change the str.setCharAt to the following:

if (Character.isUpperCase(input.charAt(i)) && i != 0) {
    str.append(' '); // adds a space
    str.append(Character.toLowerCase(input.charAt(i)); // add lowercase.
} else { // Not an upper case, so just append it normally.
    // EDIT: Added (char) cast to get the right overload of append.
    str.append((char)input.charAt(i)); 
}

Basically, what this says is "If its an uppercase letter, append a space then the lower case value, otherwise just append it as is."

Daniel
  • 4,481
  • 14
  • 34