-8

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?

Sam Gildea
  • 19
  • 1
  • 1
  • 2

6 Answers6

3

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 ");
}
Anatoly Shamov
  • 2,608
  • 1
  • 17
  • 27
gevorg
  • 4,835
  • 4
  • 35
  • 52
1

You can replace the space character with "like":

text.replace(" ", " like ");

Vojtech Kane
  • 559
  • 6
  • 21
1

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());
}
Marouane S.
  • 109
  • 4
1

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;
   }
1

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.

GauravP
  • 61
  • 1
  • 10
0

What about just replacing " " by " like " ?

http://www.tutorialspoint.com/java/java_string_replace.htm

LNRD.CLL
  • 385
  • 1
  • 5
  • 19