Answer:
// program in java.
// package
import java.util.*;
// class definition
class Main
{
// main method of the class
public static void main (String[] args) throws java.lang.Exception
{
try{
// object to read input from user
Scanner scr=new Scanner(System.in);
System.out.print("Enter a string:");
// read input
String myString=scr.nextLine();
// variable to store characters count
int char_count=0;
// count the characters
for(int i = 0; i < myString.length(); i++) {
if(myString.charAt(i) != ' ')
char_count++;
}
// print the number of character
System.out.println("total characters in the String: "+char_count);
}catch(Exception ex){
return;}
}
}
Explanation:
Read a string from user with the help of Scanner object and assign it to variable "myString".Iterate over the string and if character is not space (' ') then char_count++. After the loop print the number of characters in the string.
Output:
Enter a string:hello world
total characters in the String: 10