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

时间:2017-09-29 19:40:40

标签: java string append string-concatenation

我对Java比较陌生,但我会尽我所能抓住它!

所以在我的作业中,我被要求从用户那里获得一个输入(字符串)并在输入字符串的每个单词的末尾添加一个单词。我可能会遗漏一些东西,因为我无法弄清楚这么简单。

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

  

这就是我喜欢的方式

我希望如此:

  

这就是我现在如何看待它如何呈现

我不能在这个问题的解决方案中使用任何if / for / while语句/循环,但是,我允许使用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();
    }
}

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

2 个答案:

答案 0 :(得分:2)

这个问题已经有很多答案,但据我所知,他们都没有做对。它不适用于多个空格(因为每个空格都替换为"meow ")。或者用"meow "重新定位多个空格 - 因此空格或丢失。或者最后的空间(或没有空间)处理不正确。

所以这是我的看法:

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

结果:

Thismeow ismeow  howmeow   Imeow    likemeow    itmeow

我认为"字"是由空格字符或字符串的开头或结尾分隔的一系列非空格字符。然后是"字"的最后一个字符。是一个非空格字符,后面紧跟一个空格字符或字符串结尾。这可以通过正则表达式([^\s])(\s|$)来检测。第一组将代表单词的最后一个字符,第二组代表字符串的下一个空格或结尾。

因此,要将meow附加到每个单词,我们可以将其插入单词的最后一个字符和后面的空格/字符串结尾之间。这就是$1meow$2的作用。 $1引用正则表达式中的第一个组(单词的最后一个字符),$2 - 第二个组(在空格/字符串结尾之后)。

喵。

答案 1 :(得分:0)

您可以使用replaceAll

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

要使其适用于最后一个单词,您需要在结尾添加' '

是的,trim()最后一个空格,最初添加。