添加在.replaceAll之后替换的字符

时间:2016-07-27 23:54:35

标签: java string replaceall

我目前正在制作一个反转句子顺序的程序,但如果句子有标点符号,则需要出现在新句子的末尾。

例如:“我的名字是鲍勃。”应该成为“鲍勃是我的嗨。”

我已经编写了反转String并删除所有非单词字符所需的代码。但是,我需要知道:如何将删除的字符添加到新String的末尾。

import java.util.Scanner;
import java.util.StringTokenizer; // for splitting


public class MyTokenTester
{
    public static void main(String[] args)
    {
        Scanner enter = new Scanner(System.in);
        String sentinel = ""; // condition for do...while
        String backward = ""; // empty string 



        do
        {

        System.out.println("Please enter a sentence: ");
        String sentence = enter.nextLine();
        String[] words = sentence.split(" "); // array words gets tokens

        for (int count = words.length -1; count>=0; count--) // reverse the order and assign backward each token
        {
            backward += words[count].replaceAll("\\W", "") + " ";

        }

        System.out.println(backward); // print original sentence in reverse order

        System.out.println("Hit any key to continue or type 'quit' to stop now: ");
            sentinel = enter.nextLine();
                sentinel = sentinel.toLowerCase(); // regardless of case




        } while (!sentinel.equals("quit")); // while the sentinel value does not equal quit, continue loop

        System.out.println("Programmed by ----");



    } // end main



} // end class MyTokenTester

0 个答案:

没有答案