[英]Find the length of string in c with just one line of code without using strlen() function?
I want to find if there is any way to find the length of any string in C
. 我想找到是否有任何方法可以在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 . 因此,在一行代码中,您将获得存储在len中的字符串长度。
You can remove s[len] != '\\0';
你可以删除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. 您可以调用strlen()函数来在一行中知道字符串的长度。 it returns an size value size_t strlen(char*) 它返回一个大小值size_t strlen(char *)
just do this: 这样做:
for(len=0;s[len];len++);
this will store the length in len
这将把长度存储在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. 它是18个字节,因此它是一个非常好的代码 - 高尔夫答案。 However, I would prefer the more canonical 但是,我更喜欢更规范的
for(len = 0; s[len]; len++) ;
in real code. 在实际代码中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.