Assuming I have a String like "MikeJackson" I am trying to figure out a way to put a space in between so it becomes "Mike Jackson". And then applying the same method to another string say "JohnBull" would give me back "John Bull". This is the code I came up with:
public class Test{
public Test(){
}
public void sep(String s){
s = s + " ";
char[] charArray = s.toCharArray();
int l = s.length();
for (int i = 0; i < l; i++){
char p = ' ';
if(Character.isUpperCase(s.charAt(0))){
continue;
}
else if (Character.isUpperCase(s.charAt(i))){
int k = s.indexOf(s.charAt(i));
charArray[l] = charArray[--l];
charArray[k-1] = p;
}
//System.out.println(s.charAt(i));
}
}
public static void main (String args[]){
Test one = new Test();
one.sep("MikeJackson");
}
}
My idea was to add a space to the String so that "MikeJackson" becomes "Mike Jackson " and then shift the characters on place to the right (check for where I find an uppercase) ignoring the first uppercase. Then put a character ' ' in place of the character 'J' but shift 'J' to the right. That's what I was trying to achieve with my method but it looks I need some guidelines. If anyone could help. Thanks.
Try this:
"MikeJackson".replaceAll("(?!^)([A-Z])", " $1");
For every upper char I am adding a space before.
Also, it works with multiple uppercase words.
I am getting Word1 Word2 Word3 for Word1Word2Word3.
public static void sep(String s) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
result.append(s.charAt(i));
if (i != s.length() -1 && Character.isUpperCase(s.charAt(i + 1))) {
result.append(" ");
}
}
System.out.println(result);
}
Simply add a space if the next character is uppercase.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With