如何在不使用strlen的情况下计算字符串的字符数

问题描述:

我有任务计算随机字中的字母数,直到输入“End”。我不允许使用strlen();功能。这是我目前的解决方案:如何在不使用strlen的情况下计算字符串的字符数

#include <stdio.h> 
#include <string.h> 

int stringLength(char string[]){ 
    unsigned int length = sizeof(*string)/sizeof(char); 
    return length; 
} 

int main(){ 
    char input[40]; 
     
    while (strcmp(input, "End") != 0) { 
        printf("Please enter characters.\n"); 
        scanf("%s", &input[0]); 
        while (getchar() != '\n'); 
        printf("You've entered the following %s. Your input has a length of %d characters.\n", input, stringLength(input)); 
    } 
} 

stringLength值不正确。我究竟做错了什么?

+0

'* string'是单个字符,所以'的sizeof(*串)'是一个字符,这始终是'1'的大小。 – Barmar

+0

您需要编写一个循环来计算字符,直到它到达空终止符。 – Barmar

+3

指针不是数组不是指针。 – Olaf

%n说明符也可用于捕获字符数。
使用%39s将防止将太多字符写入数组input[40]

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

int main(void) 
{ 
    char input[40] = {'\0'}; 
    int count = 0; 

    do { 
     printf("Please enter characters or End to quit.\n"); 
     scanf("%39s%n", input, &count); 
     while (getchar() != '\n'); 
     printf("You've entered the following %s. Your input has a length of %d characters.\n", input, count); 
    } while (strcmp(input, "End") != 0); 

    return 0; 
} 

编辑纠正@chux指出的缺陷。
使用" %n来记录前导空格和%n"记录总字符,这应记录前导空格的数量和解析的总字符。

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

int main(int argc, char *argv[]) 
{ 
    char input[40] = {'\0'}; 
    int count = 0; 
    int leading = 0; 

    do { 
     printf("Please enter characters. Enter End to quit.\n"); 
     if ((scanf(" %n%39s%n", &leading, input, &count)) != 1) { 
      break; 
     } 
     while (getchar() != '\n'); 
     printf("You've entered %s, with a length of %d characters.\n", input, count - leading); 
    } while (strcmp(input, "End") != 0); 

    return 0; 
} 

EDIT stringLength()函数返回长度

int stringLength(char string[]){ 
    unsigned int length = 0; 
    while (string[length]) {// true until string[length] is '\0' 
     length++; 
    } 
    return length; 
} 
+0

伟大的解决方案!你还可以为其他人描述的方式添加一个解决方案吗? :-) – PeterPan

+1

'“%n”'会报告被解析的'char'的数量,包括前导的空格。尝试输入'“123”'和输出将会说输入是长度为4的'“123”'。 – chux

+1

对我来说看起来不错。没有看到新的问题。 – chux

请注意,sizeof评估编译时间。所以它不能用于确定运行时间中字符串的长度。

字符串的长度是直到遇到空字符时的字符数。因此字符串的大小比字符的数量多一个。这个最终的空字符被称为,终止空字符

因此,要知道运行时字符串的长度,必须计算字符数,直到遇到空字符。

用C语言编程很简单;我把这个留给你。