Here, we have a basic program example to find the length of a string using different languages. This program is created in c language, c++, Java, and Python.
Code to print the string length in C language
#include <stdio.h>
#include <string.h>
void main()
{
char str[50];
int i, len = 0;
printf("Input a string : ");
scanf("%s", str);
for (i = 0; str[i] != '\0'; i++)
{
len++;
}
printf("The length of the string %s is : %d\n\n", str, len);
}
Code to print the string length in C++ language
#include <iostream>
#include <string>
using namespace std;
int main()
{
char str[50];
int i, len = 0;
cout << " Input a string: ";
cin >> str;
for (i = 0; str[i] != '\0'; i++) {
len++;
}
cout << "So, the length of the string " << str << " is: " << len << endl;
}
Code to print the string length in Python language
str= input("Enter the string: ")
len=0
for i in str:
len=len+1
print("Length of the string", str, " is: ")
print(len)
Code to print the string length in Java language
import java.util.*;
class stringLength
{
public static void main(String args[])
{
int len=0;
String str;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the string: ");
str=sc.nextLine();
char ch[]=str.toCharArray();
for(char c : ch)
{
len++;
}
System.out.println("Length of the string "+ str + " is: "+len);
}
}