How to add space between words, without importing a library? Each word starts with a capital letter.
input:
HowAreYou
output:
how are you
This is my attempt which is not working:
public static String capSpace(String txt) {
String word = null;
for (int i = 0; i < txt.length(); i ) {
int a = txt.charAt(i);
String g = " ";
if (a == Character.toUpperCase(a)) {
word = txt.substring(0, i) " " txt.substring(i);
}
}
return word;
}
CodePudding user response:
I think you were on the right track, but we can simplify your logic a bit. Consider every character in txt
. If it is uppercase (and not the first character) add a space, then add the lowercase version of the character. Otherwise add the character. Like,
public static String capSpace(String txt) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < txt.length(); i ) {
char ch = txt.charAt(i);
if (i != 0 && Character.isUpperCase(ch)) {
sb.append(" ");
}
sb.append(Character.toLowerCase(ch));
}
return sb.toString();
}
And then to test it,
public static void main(String[] args) {
System.out.println(capSpace("HowAreYou"));
}
Which outputs (as requested)
how are you
CodePudding user response:
Do not forget about performance. You should not modify String
in a loop, because every iteration you create a new string. It's much better to use StringBuilder
:
public static String capSpace(String str) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < str.length(); i ) {
char ch = str.charAt(i);
if (Character.isUpperCase(ch) && buf.length() > 0)
buf.append(' ');
buf.append(Character.toLowerCase(ch));
}
return buf.toString();
}
CodePudding user response:
Stream.of("HowAreYou".split("(?=\\p{Upper})"))
.map(String::toLowerCase)
.collect(Collectors.joining(" "));
CodePudding user response:
Use String::replaceAll
with a regular expression (?<!^)\p{Lu}
selecting all uppercase letters except for the first letter in the string to insert the space, and then call String::toLowerCase
to change the case of entire String at once (which should have better performance than lower-casing characters one by one):
public static String capSpace(String txt) {
if (null == txt || txt.isEmpty()) {
return txt;
}
return txt.replaceAll("(?<!^)\\p{Lu}", " $0").toLowerCase();
}
Tests:
System.out.println("|" capSpace("HelloHowAreYou") "|");
Output:
|hello how are you|
CodePudding user response:
You can split
and then use static method String.join()
:
public static String capSpace(String str) {
return String.join(" ", str.split("(?=[A-Z])")).toLowerCase();
}
Then:
String str = "HowAreYou";
System.out.println(capSpace(str));
Output:
how are you