Java Examples

count non space character java

Table of Contents

NonSpaceChar.java

import java.util.Scanner;
/**
 * @author Candid Java
 */

public class NonSpaceChar {

 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  System.out.print("Enter your text: ");
  String str = input.nextLine();
  input.close();
  //this will remove all the occurrences of white spaces. 
  int nonSpaceChar = str.replaceAll("\\s", "").length();
  System.out.println("There are " + nonSpaceChar + " characters.");
 }


}

Output

Enter your text: Candid Java
There are 10 characters.