I need to write a method that puts the word "like" in between each of the words in the original sentence.
For example:
teenTalk("That is so funny!")
would return "That like is like so like funny!"
Would you use sentence split for this?
I need to write a method that puts the word "like" in between each of the words in the original sentence.
For example:
teenTalk("That is so funny!")
would return "That like is like so like funny!"
Would you use sentence split for this?
You can do it like this:
String teenTalk(String source) {
return String.join(" like ", source.split(" "));
}
or like this:
String teenTalk(String source) {
return source.replaceAll(" ", " like ");
}
You can replace the space character with "like":
text.replace(" ", " like ");
Using Java 8 :
public static void main(String[] args) {
String testJoiner = "That is so funny!";
// Split the string into list of word
List<String> splited = Arrays.asList(testJoiner.split("\\s"));
// create new StringJoiner that add the delimiter like between each entry
StringJoiner joiner = new StringJoiner(" like ");
// internal iteration over the words and adding them into the joiner
splited.forEach(joiner::add);
// printing the new value
System.out.println(joiner.toString());
}
Not very efficient but the first thing that comes to mind is something "like" this:
import java.util.StringTokenizer;
public String teenTalk(String inputString) {
String liked = "";
StringTokenizer token = new StringTokenizer(inputString);
while (token.hasMoreElements()) {
liked += token.nextToken();
if (token.hasMoreElements()) {
liked += " like ";
}
}
return liked;
}
You can do something like this
String text = "That is so funny!";
text = text.replaceAll("\\s\\b", " like ");
This will also make sure that all " like " 's come in between sentence. It will always put the "like" in between the text, not in the start or at the end. Even if the text is something like this "This is so funny! "
it will work.