In this tutorial, we will see how to Count Total Characters in a String in java.
The program below counts the number of letters present in the sentence (String) and displays the total character present in number.
The program checks for spaces present in the Strings and if gets space while checking each character then it will skip the spaces, charAt()
function is used in the following java program.
Although if you want to know about the String and loop that are used in the program below. you may click the link below:
We will see two Example:
1. Where the String is already defined in the program.
2. Where the string is taken as an input from the user.
1. Program to Count Total Character in a String in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | //count total character in a string public class CountCharString { public static void main(String[] args) { String str = "I am learning java"; int count = 0; //counting String for(int i = 0; i < str.length(); i++) { if(str.charAt(i) != ' ') count++; } //Displays the total character, space exclused System.out.println("Total character in a given string: " + count); } } |
Output:
Total character in a given string: 15
2. Program to Count Total Character in a String in Java
We will see the example where we will get the String from the user inputs in the program as shown below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | //count total character in a string (user inputs) import java.util.Scanner; public class CountCharString { public static void main(String[] args) { String str; int count = 0; Scanner in = new Scanner(System.in); //User Input System.out.println("Enter a string: "); str = in.nextLine(); //Excluding Space for(int i = 0; i < str.length(); i++) { if(str.charAt(i) != ' ') count++; } //Displays the total character, space exclused System.out.println("Total character in a entered string: " + count); } } |
Output:
Enter a string:
I am learning java
Total character in a entered string: 15