How to find Length or Size of a String

Description

* The number of character in a string is length of string.
* Blank spaces also counted as character in string.

C/C++

/* C program to find length of string */
//Save it as StringLength.c

#include<stdio.h>
#include<string.h>
int main(){

    int i=0, length;
    char str[100];

    printf("Enter a string : ");
    gets(str);

    //Loop run untill null character found
    while(str[i]!='\0'){
        i++;
    }

    length = i;

    printf("The length of string %s is %d",str,length);

    //The length of string using library function
    //It is defined in string.h

    int len = strlen(str);

    printf("\nThe length of string %s is %d",str,len);

    return 0;
Input:
Enter a string : Virat Kohli

Output:
The length of string Virat Kohli is 11
The length of string Virat Kohli is 11

Java

/* Java program to find length of string */
//Save it as StringLength.java

import java.io.*;
import java.util.Scanner;
public class StringLength {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a string : ");

        String str = scanner.nextLine();

        int length = str.length();

        System.out.println("The length of string " + str + " is " + length);

    }
}
Input:
Enter a string : 
Virat Kohli

Output:
The length of string Virat Kohli is 11

Related programs

1) Program to Convert Lowercase to Uppercase of a String
2) Program to Append one String to another String
3) Program to Compare Two Strings
4) Program to Reverse a String
5) Find Substring of a Given String
6) Program to Insert a String into Another String
7) Program to check String is Palindrome
8) Program to sort characters of strings in alphabetical order
9) Program to Sort set of strings in alphabetical order
10) Program to find frequency of occurrence of a character
11) Program to copy string
12) Program to remove vowels from a String
13) Program to Multiply Numbers Present in a String
14) Program to remove given number from a string
15) Program to Convert UpperCase to LowerCase
Share Me

Leave a Reply