Find the Length of a String without Using strlen() Function

Program to find the length of a string without using the strlen() function is discussed here. Length of a string can be found by scanning the string, character by character until an empty space ‘/0’ is encountered.

Program to find the length of a string without using strlen() function

// C program to find length of the string without using strlen() function
#include <stdio.h>
int main()
{
char s[100];
int i;

printf(“Enter a string: “);
scanf(“%s”, s);

for(i = 0; s[i] != ‘\0’; ++i);

printf(“Length of string: %d”, i);
return 0;
}

// C++ program to find length of a string without using strlen() function
#include <iostream>
using namespace std;
int main()
{
char s[100];
int i;\
cout << “\nEnter a string: “;
cin >> s;
for(i = 0; s[i] != ‘\0’; ++i);
cout << “\nLength of string : ” << i;
cout << endl;
return 0;
}

//  Java program to find the lenght of a string without using library functions

import java.util.*;
public class Main
{
public static void main(String args[]) throws Exception
{
String str;
System.out.print(“\nEnter a string : “);
Scanner sc = new Scanner(System.in);
str = sc.nextLine();
int i = 0;
for(char c: str.toCharArray())
{
i++;
}
System.out.println(“Length of the given string : ” + i);
}
}

# Python program to find length of a string without using library functions

input_str = “helloworld”
count = 0
for i in input_str:
count = count + 1
print(“Length of string : “,end = “”)
print(count)

Program to find the length of a string using pointers

// C program to find length of the string using pointers
#include<stdio.h>
#include<conio.h>

int length_of_string(char*p)
{
int count = 0;
while (*p != ‘\0’) {
count++;
p++;
}
return count;
}

int main()
{
char str[100];
int length;
printf(“\nEnter any string : “);
gets(str);
length = length_of_string(str);
printf(“\nThe length of the given string : %d\n”, length);
return 0;
}

// C++ program to find length of a string using pointers
#include <iostream>
using namespace std;

int length_of_string(char*p)
{
int count = 0;
while (*p != ‘\0’) {
count++;
p++;
}
return count;
}

int main()
{
char str[50];
int length;
cout << “\nEnter any string : “;
cin >> str;
length = length_of_string(str);
cout << “\nThe length of the given string : ” << length;
cout << endl;
return 0;
}

length of a string