user3916111
user3916111

Reputation: 1

using string methods to count characters

I'm trying to count the number of non-blank characters in a string.

It works fine when there are no leading blank spaces, but when I add 3 spaces in from, it doubles the number of non-blank characters.

This is my code:

import java.io.*;
import java.util.*;

public class countCharacters
{

public static void main(String[] args) throws Exception
{
  String str1;
  int count;
  count = 0;



  BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a string: ");
  str1 = dataIn.readLine();
while(str1.length() > 0)
      {


  System.out.println("The String ''" + str1 + "''");
  System.out.println("has " + str1.length() + " Characters, including all blanks.");
  for(int i=0; i < str1.length(); ++i)
    if(str1.charAt(i) !=' ')
    count++;
  str1 = str1.trim();
   System.out.println("and " + str1.length() + " Characters, trimmed of leading and trailing blanks.");
   System.out.println("and " + count + " non-blank characters.");
System.out.println("");

System.out.print("Enter a string: ");
  str1 = dataIn.readLine();
   }

  System.out.println("Program complete.");

}
}

Upvotes: 0

Views: 114

Answers (4)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79875

Are you sure that it doubles the count every time? Maybe this only happens on the second time through the main loop?

You should be resetting count when you enter a new string. Otherwise, you're just adding to the count from the previous time through the main loop. Add a line like count = 0; before the System.out.print("Enter a string: "); at the bottom of the main loop, or declare and initialise count inside the loop, rather than before the loop.

Upvotes: 1

Matias Cicero
Matias Cicero

Reputation: 26331

Have you tried using the static method:

Character.isWhitespace(char ch);

For example,

if(!Character.isWhitespace(str1.charAt(i)))
    count++;

Upvotes: 0

vsnyc
vsnyc

Reputation: 2257

You could simply do

String temp = str1.replaceAll("\\s+","");

temp.length() will give you the answer.

You can get rid of temp variable if modifying str1 is an option

Upvotes: 0

azurefrog
azurefrog

Reputation: 10955

A much cleaner way to do this would be to just make a copy without any spaces and compare the lengths:

    String str1 = "  the quick brown fox  ";
    String spaceless = str1.replace(" ", "");
    System.out.println("Number of spaces: "+(str1.length() - spaceless.length()));

Upvotes: 0

Related Questions