954,541 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Counting all Non-blank Characters in a String

I am just starting out at JAVA and trying to write a program that counts all characters in a string, counts all characters minus trailing and leading blanks and also counts all non-blank characters. Here is what I have so far. I am stuck on the non-blank character counts. Can anyone provide some help on this? The countChar always returns 0...

import java.util.Scanner;

public class Count {

	public static void main(String[] args) {
		
		for (int count = 1; count <= 5; count ++) {
		
		System.out.println("Please enter some text: ");
		Scanner keyboard = new Scanner(System.in);
		String text = keyboard.nextLine();
		
		int HowLong = text.length();
		String MinusTrailing = text.trim();
		int CMinusTrailing = MinusTrailing.length();

		String NB = MinusTrailing;
	    int countChar = 0;
	    int limit = NB.length();
	
	    for(int i = 0; i < limit; ++i)
	    {		  
	      if(Character.isWhitespace(NB.charAt(i)))
	        {		  
		      ++count;
	      }
	        }	 		
				
		System.out.println(HowLong);
		System.out.println(CMinusTrailing);
		System.out.println(countChar );
	
	
		}
		
	}

}


Thanks!

Kevin008
Newbie Poster
2 posts since Sep 2007
Reputation Points: 10
Solved Threads: 0
 

I think you want to increment "countChar "instead of "count" in this statement

if(Character.isWhitespace(NB.charAt(i)))
 {
   ++count;
 }


:)

Ezzaral
Posting Genius
Moderator
15,986 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847
 
I think you want to increment "countChar "instead of "count" in this statement

Got it!! Thank you so much!!!

Kevin008
Newbie Poster
2 posts since Sep 2007
Reputation Points: 10
Solved Threads: 0
 
int countChar = string.replaceAll("\\s*", "").length();


Just to be an @ss! ;-)

masijade
Industrious Poster
Moderator
4,253 posts since Feb 2006
Reputation Points: 1,471
Solved Threads: 494
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You