0

I want to write a program that will insert the word "like" in between the spaces of each word in a sentence. What I have attempted so far:

public String teenTalk(String sentence)
{
    for (int i = 0; i < sentence.length(); i++)
    {
       char sentC = sentence.charAt(i);
       String sentS = Character.toString(sentence);
       if (sentS.equals(" "))
       {
           sentence = sentence.replaceAll(" ", " like ");
       }
        return sentence;
    }

Please excuse any inefficiencies as I am still relatively new to programming in general. I recently got intensely into Strings and Chars, but I still lack much knowledge in how they work, so I'm guessing my code has illogical errors. I'd be thankful if someone could point them out.

I did find another forum on this (Write method that puts the word "like" in between each of the words in the original sentence) asking for the same thing. However, the website that I have to turn this assignment into has an IDE that is extremely limited and will not compile tokens or lists. I have yet to test .replace and .replaceAll but I will place an update after I get my attempted code fixed. Thanks for any help inadvance

Aldwoni
  • 1,168
  • 10
  • 24
Harry You
  • 87
  • 2
  • 3
  • 11
  • I'm not understanding the answers from the apparently duplicate question that I was linked to. Could I ask where I was going wrong? Did it have to due with the immutability of Strings? – Harry You Nov 13 '16 at 23:05
  • Yes, `sentence.replaceAll` does not modify `sentence`. It returns a new String, so you need `sentence = sentence.replaceAll`. – Tunaki Nov 13 '16 at 23:10
  • My code still isn't working. I'm sorry to ask but are you able to see any error in my syntax? – Harry You Nov 14 '16 at 00:50
  • Your code doesn't compile, at least not in standard Java; there is no `Character.toString` method that takes a `String`. If I change the argument to `sentC` instead of `sentence` it produces an 'infinite' loop which tries to make the string infinitely long, although actually it dies when JVM heap is exhausted. `String.replaceAll` does what the name says, replace all occurrences, so you only need to call it once and only should call it once. – dave_thompson_085 Nov 14 '16 at 07:53

0 Answers0