Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading the number of non-blank characters within string

Tags:

java

This is my simple code.

import java.util.Scanner;

public class WordLines
{
    public static void main(String[] args) 
    {
        Scanner myScan = new Scanner(System.in);
        String s;

        System.out.println("Enter text from keyboard");

        s = myScan.nextLine();

        System.out.println("Here is what you entered: ");
        System.out.println(s.replace(" ", "\n"));
    }
}

If I were to enter a sentence such as "Good Morning World!" (17 non-blank characters in this line)

How could I be able to display my text and on top of that print out the number of non-blank characters present.

like image 525
user2086204 Avatar asked Feb 19 '13 09:02

user2086204


2 Answers

Use a regex to delete all whitespace (spaces, newlines, tabs) and then simply take the string length.

input.replaceAll("\\s+", "").length()
like image 61
Marko Topolnik Avatar answered Oct 23 '22 09:10

Marko Topolnik


Try this:

System.out.println(s);
System.out.println(s.replace(" ", "").length());
like image 25
cowls Avatar answered Oct 23 '22 08:10

cowls