Count Number of characters of the Character Array

Count Number of characters of the character Array” is basically a problem of finding length of the character array. Here, we are given a character array and our task is to count the number of characters of the character array.

The number of characters of the character array is same as the size of the character array. 

Different programming languages have different in-built function to find the length of the string/character array.

Example:

Input:
Abcdef
Output:
6

Method 1: Without using in-built function

We know that the last character of the character array is NULL character (‘/0’). So, to find the length of character array, we will initialize a variable as res = 0 and traverse the complete character array, until we find the NULL character. While traversing, we will increment the res by 1 for every character encountered.

C++ Program to count the number of characters of the string is as follows:

#include<bits/stdc++.h>
#define len 1000   
using namespace std;  
int main()    
{  
    char str[len];  
    cout<<"Enter the string:\n";  
    cin>>str;  
    int res = 0;  
    /* In character array, last character is always null character('\0'), 
       we will loop till null character is not found*/  
    for(int i = 0 ; i < len && str[i]!='\0' ; i++)  
    {  
        res++;  
    }  
    cout<<"\nThe number of characters of the "<<str<<" are: ";  
    cout<<res;  
}  

OUTPUT:
Enter the string: sdfdfv
The number of characters of the sdfdfv are 6
Time Complexity:
O(n), where n is the length of string.

Method 2: With using in-built function

In C Programming language, to find the length of the character array, we can use the in-built function strlen() which comes with header file string.h .

C++ Program to count the number of characters of the string is as follows:

#include<bits/stdc++.h>  
#define len 1000
using namespace std;  
int main()   
{  
    char str[len];  
    cout<<"Enter the string:\n";  
    cin>>str;  
    int res = strlen(str);  
    cout<<"\nThe number of characters of the "<<str<<" are: ";  
    cout<<res;  
}  

OUTPUT:
Enter the string: sdfdfv
The number of characters of the sdfdfv are 6
Time Complexity:
O(n), where n is the length of string.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *