Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the length of string in c with just one line of code without using strlen() function?

Tags:

arrays

c

string

I want to find if there is any way to find the length of any string in C.
Here's how I did:

#include <stdio.h>
int main()
{
    char s[10] = "hello";
    int i , len = 0;
    for(i = 0; s[i] != '\0'; i++)
    {
        len++
    }
    printf("length of string is: %d" , len);
    return 0;
}

I want to find, if there is any way to get the length of string in just one line of code.

like image 791
hello world Avatar asked Dec 05 '22 15:12

hello world


2 Answers

You can just simply do this:

for(len = 0; s[len] != '\0'; len++);

So in just one line of code you will get the length of string stored in len.

like image 54
dhruw lalan Avatar answered Feb 09 '23 01:02

dhruw lalan


You can remove s[len] != '\0'; comparison to make it shorter:

for(len=0;s[len];len++);
like image 38
algojava Avatar answered Feb 08 '23 23:02

algojava