Table of contents
1.
Introduction
2.
What is a string?
2.1.
Strings in Java
3.
Solution Approach 1(Using For loop)
3.1.
Algorithm:
3.2.
Program:
3.2.1.
Output:
4.
Solution Approach 1(Using While loop)
4.1.
Algorithm:
4.2.
Program:
4.2.1.
Output:
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024

Number of Characters in a String

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

This article will teach you how to find the total number of characters in a string. We will go through the basics of strings in java then learn how to construct a program that will count the total number of characters in a string.

Strings are Objects in Java that are internally supported by a ‘char array.’ We will iterate through the string and count the characters to get the total number of characters present in the string. We will discuss two programs to count characters in a string, one using for loop and the other using while loop. We hope after going through the post, you will be able to code these programs on your own. Let’s get started by learning a few basic concepts.

What is a string?

The series of characters used to convey text information is called a string. We define a string as a one-dimensional array of characters that must permanently terminate in the unique character '\0' (NULL). Because each character takes up one byte of memory and a string always ends with a null character, the character array used to store the string is always one size larger than the number of characters in the string/word.

Strings in Java

A string is a data structure that represents a series of characters. The string is represented in Java by the String class found in java.lang package.

Example:

String str= "Hello";
You can also try this code with Online Java Compiler
Run Code

Solution Approach 1(Using For loop)

Now, that you have learnt a few concepts of java strings, we will go through the program to count the total number of characters in a string. In the first program discussed below, we will iterate through the string using a for loop and count the characters to get the total number of characters present in it. So, we start with the algorithm of the program to have a better understanding of the program, how it actually works.

Algorithm:

  1. Start
  2. Make a string declaration.
  3. Set the string's initial value.
  4. Declare and initialise a variable to count the total number of characters in the given string.
  5. To calculate the same, use a for a loop.
  6. To avoid counting space, use an if condition.
  7. Each time a character appears, increase the count.
  8. Display the total number of characters in the provided string.
  9. Stop.

Program:

/*Using a for loop, count the total number of characters in a string in Java.*/
public class totalchar
{
  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++;    
        }                
        //below code displays the number of characters in string.    
        System.out.println("The string contains number of characters: " + count);    
    }      
}
You can also try this code with Online Java Compiler
Run Code

Output:

We used the for loop in this Java example to iterate a string from beginning to end. We used an if statement within that loop to see if the character was not empty. If this is the case, the count value will rise from 0 to 1.

Time-Complexity: O(N)
Check out this problem - Longest String Chain, and Duck Number in Java.

Solution Approach 1(Using While loop)

We learnt to count the total number of characters of a predefined string using for loop above. Now, we will use a while loop to iterate through the string and count the characters to determine the total number of characters. Here, we'll ask the user for the input string and then use a while loop to figure out how many characters are in the string.

Algorithm:

  1. Start.
  2. Declare and initialise a variable to count the total number of characters in the given string.
  3. Declare a string and request that the user initialise it.
  4. Find the total number of characters in a string using the while loop.
  5. To prevent counting spaces, use an if condition.
  6. If a character encounters, increase the count variable.
  7. Display the total number of characters in the input string.
  8. Stop.

Program:

/* Using while loop, count the total number of characters in a string in Java.*/
import java.util.*;
public class totalchar
{
  public static void main(String[] args)
  {    
        //Take the user's input.
  int count = 0, i = 0; 
        Scanner sc=new Scanner(System.in);   
        System.out.print("To Count Characters, Please Enter a String =  ");
        String str = sc.nextLine();
        //Use a while loop to compute the number of characters in the string.
        while(i < str.length())
        {
            if(str.charAt(i) != ' ')
            {
                count++;
            }
            i++;
        }      
        System.out.println(" Total number of characters in provided string is = "+ count);        
    }      
}
You can also try this code with Online Java Compiler
Run Code

Output:

We iterated the string from beginning to end using the while loop in this Java example. We used an if statement within the while loop to check if the character was not empty.

Time-Complexity: O(N)

Practice it on online java compiler for better understanding.

Also check out Addition of Two Numbers in Java here.

FAQs

  1. What are the few basic Java programmes to practice?
    Here is a list of a few basic java programmes that you can practice:
    → Java Calculator Program
    → Recursion in a Factorial Program
    → The Fibonacci Series program
    → Palindrome Program
    → Programs for permutation and combination
    → Pattern printing Programs
    → String reversal program
     
  2. What type of language is Java?
    The Java Programming Language is a class-based object-oriented language that is general-purpose, concurrent, and tightly typed.
     
  3. What is an array in Java?
    We define an array in java as a container object which can store a predefined number of values of a single type. We determine the length of an array at the time of its creation. Once we create an array in java, we can not change its length.
     
  4. What is the purpose of Java?
    Java is simple to use, making it easier to write, build, debug, and learn than other programming languages. Java is an object-oriented programming language. Java enables you to design modular programmes and helps in code reusability. Java is a platform-independent language.

Key Takeaways

We learned how to calculate the total number of characters in a string in this article. We started with the basics of java strings. Then we used two Java programmes to figure out how many characters are in a string. In the first programme, we used a for loop to compute the total number of characters in a predefined string. In the second programme, we used a while loop to calculate the same thing, except this time the input came from the user.

We hope that this blog has increased your understanding of basic java programming, and if you want to learn more, visit our articles on ‘print characters in a string’ and ‘selenium interview questions.’ Please upvote our blog to assist other ninjas in their development.

Recommended Readings:

 

Recommended problems -

 

Go to our practice platform Coding Ninjas Studio to get started. Here you can practice top problems, attempt mock tests, read interview experiences, and more.!

Happy Reading!

Live masterclass