【发布时间】: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 问题