代码之家  ›  专栏  ›  技术社区  ›  christopherson

如何对用户输入字符串使用多个替换?[副本]

  •  -1
  • christopherson  · 技术社区  · 6 年前

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

    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.");
            }
    
        }
    }
    
    2 回复  |  直到 6 年前
        1
  •  3
  •   Pshemo    6 年前

    您可以使用 replaceAll 使用regexp。

    tempPhrase = sentence.replaceAll("[.,!?:;]" , " ");
    
        2
  •  3
  •   Bentaye    6 年前

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