在 Java 中插入部分字符串

Inserting parts of a String in Java

我目前正在学校学习 Java,但我很难完成这项作业。你应该做的是拿一个字符串并在每个单词之间插入 "like" 使其成为 "teen talk" 即我喜欢爱喜欢代码。

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;

}

有谁知道我如何将 "like" 插入某个位置,以及如何让它插入它应该插入的空间?如您所见,我在制作无限循环时也遇到了问题。

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

strings 是不可变的,这意味着每次你操作(即 substring 方法在你的情况下)一个特定的 string 你会得到一个新的 string 和原始 string 修改。或者,您可以使用 StringBuilder (mutable) or use the String#replace 方法。

使用 String#replace:

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

使用 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();
}

假设这是输入:

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

输出:

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

在此处了解有关 StringJoiner 的更多信息https://www.mkyong.com/java8/java-8-stringjoiner-example/