Example 1:
Input: a = "Java is awesome" Output: Total characters without spaces : 13
1. Using charAt() to Count Total Characters in a Java String
This is the first approach, we are going to use to count characters in a String in Java.
Here we are going to iterate over the string and increase our counter for every time the character is nonspace.
Request: Before reading the code, read the algorithm and try on your IDE.
Algorithm
- Let a = “Java is awesome”
- Let counter = 0
- Using for loop to iterate over each index of the string
- If any character is not space, then we’ll increase the counter
- printing the counter as the count of total characters
Code
public static void main(String[] args) { | |
String input ="Java is awesome"; | |
int counter=0; | |
for (int i = 0; i < input.length(); i++) { | |
// if character is not space, increase the counter | |
if (input.charAt(i)!=' ') | |
{ | |
counter++; | |
} | |
} | |
System.out.println("Total characters without spaces : "+counter); | |
} |
Total characters without spaces : 13
2. Using Java 8 Stream to Count Characters in a Java String
This is the second method used for counting characters in a String in Java.
We will be using the new Java 8 Streams in this method.
Request: Before reading the code, read the algorithm and try on your IDE.
Algorithm
- Let a = “Java is awesome”
- Then we’ll put variable count equal to input.chars().filter(ch –> ch!=‘ ‘).count() which is going over each character and checking if it’s space or not, For all non-space characters, it puts the total count in the count variable.
- printing the count as the count of total characters
Code
public static void main(String[] args) { | |
String input = "Java is awesome"; | |
int count = (int) input.chars().filter(ch -> ch!=' ').count(); | |
System.out.println("Total characters without spaces : " + count); | |
} |
Total characters without spaces : 13
3. Using String.length() to Count Total Characters in a Java String
This is the easiest way to find the total count of characters in a String.
We will be using the basic .length() method in order to find the total count.
In order to disclude spaces from our count, we will replace all space characters with non-space characters.
Request: Before reading the code, read the algorithm and try on your IDE.
Algorithm
- Let a = “Java is awesome”
- Now, replace all space characters with non-space characters using replace() method
- printing the count as the count of total characters using .length() method
Code
public static void main(String[] args) { | |
String input = "Java is awesome"; | |
String inputWithoutSpaces = input.replace(" ",""); | |
// System.out.println(inputWithoutSpaces); // String without spaces | |
int count = inputWithoutSpaces.length(); | |
System.out.println("Total characters without spaces : " + count); | |
} |
Total characters without spaces : 13