GeekyMeow GeekyMeow - 3 years ago 141
Java Question

Appending a string at the end of each word of an input string in Java

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?

Answer Source

You can use String.join in combination with String.split:

String userString = "This is how I like it"; // obviously you will read this from the input
System.out.println(String.join("meow ", userString.split("\\s+")).concat("meow"));

Output

Thismeow ismeow howmeow Imeow likemeow itmeow

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download