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.
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 .
You can remove s[len] != '\\0';
comparison to make it shorter:
for(len=0;s[len];len++);
You can call strlen() function to know length of the string in one line. it returns an size value size_t strlen(char*)
just do this:
for(len=0;s[len];len++);
this will store the length in len
If you want only one line, the something like this is also possible:
while (s[len] != '\0') len++;
Which is just another way of doing it, but not most pleasing to look at.
The most minimal 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);
}
It prints:
The length of string 'hello' is: 6
I believe, this should be the shortest version:
for(l=-1;s[++l];);
It's 18 bytes, so it's quite a good code-golf answer. However, I would prefer the more canonical
for(len = 0; s[len]; len++) ;
in real code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.