Write a Program to print Length of the string without using strlen() function

28 September 2022

Write a Program to print Length of the string without using strlen() function


If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023

Description

Get a string as input from user and print the length of the string without using strlen() function.

 

Input

Hello

Output

5

 

C Program

#include <stdio.h>

#include<string.h>

int main()

{

    char str1[50]={0};

    char c;

    int i=0;

    printf("Enter a string: ");

    fgets(str1,sizeof(str1),stdin);

    while(1)

    {

        c=str1[i];

        if(c=='\n')

        break;

        i++;

    }

    printf("length of string is: %d\n",i);

 

    return 0;

}

 

C++ Program

#include <iostream>

#include<string.h>

using namespace std;

int main()

{

    char str1[50]={0};

    char c;

    int i=0;

    cout<<"Enter a string: ";

    fgets(str1,sizeof(str1),stdin);

    while(1)

    {

        c=str1[i];

        if(c=='\n')

        break;

        i++;

    }

    cout<<"length of string is: "<<i;

 

    return 0;

}

 

 

 

Java

import java.util.Scanner;

public class Main

{

              public static void main(String[] args) {

                  int i=0;

                  Scanner sc = new Scanner(System.in);

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

                             String str1 = sc.nextLine();

        char ch[]=str1.toCharArray();

    for(char c : ch)

    {

        i++;

    }

              System.out.println("Length of the string = "+i);

              }

}

 

Python

str1 = input("Enter a string: ")

count = 0

for s in str1:

      count = count+1

print("Length of the string is:", count)


If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023
Related Articles

Ask Us Anything !