如何在用户输入字符串中使用多个替换? [重复]

问题描述 投票:-1回答:2

这个问题在这里已有答案:

我试图用用户输入的字符串中的空白字符替换多个字符。该计划的最终目标是计算单词并将标点符号计为空格。比如嘿......算作两个字的人。但是,只有我的最后一次更换工作,我知道为什么,但我不知道如何在不创建多个变量的情况下解决问题,而且我也不想使用数组。所以这是我的代码。

import java.util.Scanner; 
class CountWords
{
    public static void main(String args[])
    {

        Scanner scn=new Scanner(System.in);
        int wordCounter=0;
        String sentence;
        String tempPhrase = "";

        System.out.print("Enter string >>> ");
        sentence = scn.nextLine();
        tempPhrase = sentence.replace('.' , ' ');
        tempPhrase = sentence.replace(',' , ' ');
        tempPhrase = sentence.replace('!' , ' ');
        tempPhrase = sentence.replace('?' , ' ');
        tempPhrase = sentence.replace(':' , ' ');
        tempPhrase = sentence.replace(';' , ' ');

        for(int x=0; x < tempPhrase.length()-1; ++x)
        {
            char tempChar = tempPhrase.charAt(x);
            char tempChar1 = tempPhrase.charAt(x+1);
            if(Character.isWhitespace(tempChar) && 
            Character.isLetter(tempChar1))
                ++wordCounter;
        }


        ++wordCounter;
        if (wordCounter > 1)
        {
            System.out.println("There are " + wordCounter + " words in the 
            string.");
        }
        else
        {
            System.out.println("There is " + wordCounter + " word in the 
            string.");
        }

    }
}
java input character
2个回答
3
投票

你可以使用replaceAll和正则表达式。

tempPhrase = sentence.replaceAll("[.,!?:;]" , " ");

3
投票

sentence永远不会被修改,字符串是不可变的,replace每次都返回一个新的字符串。

你需要这样做:

tempPhrase = sentence.replace('.' , ' ')
    .replace(',' , ' ')
    .replace('!' , ' ')
    .replace('?' , ' ')
    .replace(':' , ' ')
    .replace(';' , ' ');

要么

tempPhrase1 = sentence.replace('.' , ' ');
tempPhrase2 = tempPhrase1.replace(',' , ' ');
tempPhrase3 = tempPhrase2.replace('!' , ' ');
tempPhrase4 = tempPhrase3.replace('?' , ' ');
tempPhrase5 = tempPhrase4.replace(':' , ' ');
tempPhrase = tempPhrase5.replace(';' , ' ');
© www.soinside.com 2019 - 2024. All rights reserved.