C语言 如何计算字符串中的字符数(如果不是占用所有空格)



我有这段代码:

char* input = malloc(sizeof(char)*100);
scanf("%s", input);        //let's say that the number of chars in "%s" is 5

如何计算我输入了多少个字符 (5(?我尝试使用 sizeof((,但找不到解决方案。

编辑(更好的解释(:输入变量最多可以托管 100 个字符,但假设我输入终端"abcde":然后它只托管 5 个字符,其他 95 个字符不被占用。我想计算那个"5"。

你必须找到空终止符。

int i = 0;
while(input[i] != 0) {
++i;
}
//i marks the spot

但是,是的,strlen(( 做得更好,因为它有一些改进/优化的搜索,因为它使用 word(16/32/64? bit( 比较和其他东西。

相关内容

最新更新