简体   繁体   中英

Inserting parts of a String in Java

I am currently learning Java in school and I am having a hard time with this one assignment. What you are supposed to do is take a string and insert "like" in between every word to make it "teen talk" ie I like love like to like code.

public String teenTalk(String sentence)
{
   for (int i = 0; i < sentence.length(); i++)
   {
       if(sentence.substring(i, i+1).equals(" "))
       {
           System.out.println("like");

       }
   }

   return sentence;

}

Does anyone know how I would insert "like" in a certain location, and how I could make it insert in the spaces that it is supposed to? As you can see, I have also been having problems with making infinite loops.

What you are supposed to do is take a string and insert "like" in between every word to make it "teen talk".

strings are immutable meaning each time you manipulate ( ie substring method in your case) a particular string you'll get a new string back and the original string is not modified. Alternatively, you could either use a StringBuilder (mutable) or use the String#replace method.

using String#replace :

public String teenTalk(String sentence){
     return sentence.replace(" ", " like ");
}

using a StringBuilder :

public String teenTalk(String sentence) {
       StringBuilder builder = new StringBuilder();
       for (int i = 0; i < sentence.length(); i++) {
           if(sentence.charAt(i) == ' '){
              builder.append(" like ");
           }else{
              builder.append(sentence.charAt(i));
           }
       }
       return builder.toString();
}

assuming this is the input:

System.out.println(teenTalk("teen talk"));

output:

teen like talk
String text = "I love coding"; //Any string you wish
StringJoiner sj= new StringJoiner(" like "); //here,"like" is the Join you need between every word
Arrays.asList(text.split(" ")).forEach(word -> sj.add(word)); //we are splitting your text and adding each word. This will insert "like" after every addition except the last
System.out.println(sj.toString()); // Converting to String

Learn more about StringJoiner here https://www.mkyong.com/java8/java-8-stringjoiner-example/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM