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

I want to find if there is a way to find the length of any string in C.
How I did it:

#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 a way to get the line length in only one line of code.

+4
source share
7 answers

You can simply do this:

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

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

+8
source

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

for(len=0;s[len];len++);
+3
source

strlen(), . size_t strlen (char *)

+2
source

just do this:

for(len=0;s[len];len++);

this will keep the length in len

+2
source

If you want only one line, something like this is also possible:

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

This is just another way to do this, but not very nice to watch.

0
source

The smallest version:

#include <stdio.h>

int main(void)
{
  char s[10] = "hello", *p = s;

  while(*p++); /* "counting" here */

  printf("The length of string '%s' is: %td" , s, p - s);
}

He prints:

The length of string 'hello' is: 6
0
source

I believe this should be the shortest version:

for(l=-1;s[++l];);

This is 18 bytes, so this is a good golf code. However, I would prefer a more canonical

for(len = 0; s[len]; len++) ;

in real code.

0
source

Source: https://habr.com/ru/post/1669504/


All Articles