【问题标题】:How can use multiple replacements with a user input string? [duplicate]如何对用户输入字符串使用多个替换? [复制]
【发布时间】:2018-03-05 15:37:26
【问题描述】:

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

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.");
        }

    }
}

【问题讨论】:

  • 第一次替换后,你应该去tempPhrase = tempPhrase.replace(...)
  • @Pshemo 抱歉,我不知道 replaceAll 问题

标签: java input character


【解决方案1】:

您可以将replaceAll 与正则表达式一起使用。

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

【讨论】:

  • @Pshemo 谢谢。引文是一个非常愚蠢的错误。我最近只是用 javascript 编程很多。
【解决方案2】:

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(';' , ' ');

【讨论】:

    猜你喜欢
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2020-04-01
    • 2014-02-16
    相关资源
    最近更新 更多