I'm relatively new to Java but I'm trying my best to get a hold of it!
So in my assignment, I was asked to get an input from the user(string) and append a word to the end of every word of the input String. I'm probably missing something because I can't figure out something so simple.
For example, we get the input from the user
This is how I like it
And I would like it as:
Thismeow ismeow howmeow Imeow likemeow itmeow
I can not use any if/for/while statements/loops in the solution of this problem, however, I'm allowed to use Java String Class API
This is the code I have so far
public class Exercise2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a string : ");
String userString = scan.nextLine();
String inputString = "meow";
//I'm aware that for the next like concatenating is just adding
//the word meow with the last word of the userString.
String newString = userString.concat(inputString);
scan.close();
}
}
Question: How do I get the desired output?
This question has a number of answers already, but as far as I can say, none of them get it right. Either it does not work with multiple spaces (as every space is replaced with "meow "
). Or multiple spaces are repaced with "meow "
- thus spaces or lost. Or space at the end (or absence thereof) is not handled correctly.
So here's my take:
String userString = "This is how I like it";
System.out.println(userString.replaceAll("([^\\s])(\\s|$)", "$1meow$2"));
Results in:
Thismeow ismeow howmeow Imeow likemeow itmeow
I assume that "word" is a sequence of non-space characters delimited by space characters or beginning or end of the string. Then last character of the "word" is a non-space character which is immediately followed by a space character or end of string. This can be detected by a regex ([^\s])(\s|$)
. First group will represent the last character of the word, second group - the following space or end of string.
So to append meow
to each word we could insert it between the last character of the word and the following space/end of string. This is what $1meow$2
does. $1
references the first group from regex (last character of the word), $2
- the second group (following space/end of string).
Meow.