In this post you will see the basic java string program that count the total number of characters in a string.
Here, first we understand that what is string,
String:
String is a sequence of characters; string is immutable that means once we created a string, we can’t change its value. In Java the String class found in java.lang package.
Example: String s =”Hello”;
Problem:
Example of the problem –
Input :
Enter a string: Hello, World!
Output :
Total number of characters in this string : 13
Explanation:
in this example we entered the string “Hello, World!“, and the program calculated that it has 13 characters.
Solutions:
There are few ways to find the number of characters in string:
- using length() method.
- using for or while loop.
First, length() method returns the number of characters in the string, including whitespace and other non-visible characters.
Approach 1 : using length() method:
class Main { public static void main(String []args){ String s ="Hello World"; // declare and initialize string int count =s.length(); System.out.println("The string has "+count+" characters"); //print the total characters } }
Output:
The string has 5 characters
Approach 1 : using for Loop:
Algorithm:
- Start
- Make a string declaration and initial value.
- Declare and initialize a variable to count the total number of characters in the given string.
- To calculate the same, use a for a loop.
- To avoid counting space, use an if condition.
- Each time a character appears, increase the count.
- Display the total number of characters in the provided string.
- Stop.
public class Main { public static void main(String[] args) { int count = 0; String str = "Hello World"; System.out.println("The given string: "+str); //Except for the space, count the characters in the string. for(int i = 0; i < str.length(); i++) { if(str.charAt(i) != ' ') count++; } //displays the number of characters in string System.out.println("The string contains number of characters: " + count); } }
Output:
The given string: Hello World The string contains number of characters: 10
More java String programs:
Java program to reverse a string
Java Program to check a String is Palindrome or not
Java Program to Get Input from User