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.
Use a regex to delete all whitespace (spaces, newlines, tabs) and then simply take the string length.
input.replaceAll("\\s+", "").length()
Try this:
System.out.println(s);
System.out.println(s.replace(" ", "").length());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With