-1

I am trying to replace multiple characters with white-space characters from a user inputted string. The ultimate goal of the program is to count the words and count punctuation as white space. Such as hey...man counting as two words. However, only my last replacement works, I know that why, but I do not know how to remedy the issue without creating multiple variables to do so, and I do not want to use an array either. So here is my code.

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

    }
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
christopherson
  • 383
  • 3
  • 6
  • 20

2 Answers2

3

sentence is never modified, Strings are immutable, replace returns a new String every time.

You need to do it this way:

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

or

tempPhrase1 = sentence.replace('.' , ' ');
tempPhrase2 = tempPhrase1.replace(',' , ' ');
tempPhrase3 = tempPhrase2.replace('!' , ' ');
tempPhrase4 = tempPhrase3.replace('?' , ' ');
tempPhrase5 = tempPhrase4.replace(':' , ' ');
tempPhrase = tempPhrase5.replace(';' , ' ');
Bentaye
  • 9,403
  • 5
  • 32
  • 45
3

You can use replaceAll with a regexp.

tempPhrase = sentence.replaceAll("[.,!?:;]" , " ");
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95