在 Java 中输入字符串的每个单词的末尾附加一个字符串

Appending a string at the end of each word of an input string in Java

我对 Java 比较陌生,但我正在尽最大努力掌握它!

所以在我的作业中,我被要求从用户那里得到一个输入(字符串)并在输入字符串的每个单词的末尾附加一个单词。我可能遗漏了一些东西,因为我想不出这么简单的东西。

例如, 我们从用户那里得到输入

This is how I like it

我希望它是:

Thismeow ismeow howmeow Imeow likemeow itmeow

我不能在这个问题的解决方案中使用任何if/for/while statements/loops,但是,我可以使用Java String Class API

这是我目前的代码

public class Exercise2 {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        System.out.println("Please enter a string : ");
        String userString = scan.nextLine();

        String inputString = "meow";

        //I'm aware that for the next like concatenating is just adding
        //the word meow with the last word of the userString.
        String newString = userString.concat(inputString);

        scan.close();
    }
}

问题:如何获得所需的输出?

你可以使用 replaceAll

userString = userString + " ";
userString =userString.replaceAll("\s+"," ");  // removing multiple spaces
userString = userString.replaceAll(" ","meow ");

要使其适用于最后一个词,您需要在末尾附加 ' '

是的,trim() 最后一个 space,这是最开始添加的。

这个问题已经有很多答案,但据我所知,none 个回答正确。要么它不适用于多个 spaces(因为每个 space 都被 "meow " 替换)。或者多个 space 被替换为 "meow " - 因此 space 或丢失。或末尾的 space(或缺少)未正确处理。

所以这是我的看法:

    String userString = "This is  how   I    like    it";
    System.out.println(userString.replaceAll("([^\s])(\s|$)", "meow"));

结果:

Thismeow ismeow  howmeow   Imeow    likemeow    itmeow

我假设 "word" 是由 space 个字符或字符串的开头或结尾分隔的非 space 字符序列。然后 "word" 的最后一个字符是一个非 space 字符,紧接着是 space 字符或字符串结尾。这可以通过正则表达式 ([^\s])(\s|$) 检测到。第一组将代表单词的最后一个字符,第二组 - 以下 space 或字符串结尾。

所以要将 meow 附加到每个单词,我们可以将其插入单词的最后一个字符和字符串的后续 space/end 之间。这就是 meow 所做的。 </code> 引用正则表达式中的第一组(单词的最后一个字符),<code> - 第二组(在字符串的 space/end 之后)。

喵.