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

标签 c counting strlen

我的任务是计算随机单词中的字母数量,直到输入“End”。我不允许使用 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 值不正确。我做错了什么?

最佳答案

%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;
}

编辑stringLength()函数以返回长度

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

关于c - 如何在不使用strlen的情况下计算字符串的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33533177/

相关文章:

c - 为什么 `struct stat` 中的字段名为 st_something?

c - 将整数分配给取消引用的字符指针

MySQL 数据透视表计数

更改传递的文件名的扩展名

c - OpenMP pragma 指令是否需要花括号?

c - shmat() 失败,返回 "Identifier removed"

javascript - 使用javascript,我如何计算亚洲字符和英文单词的混合

python - 如何使用对应字典重命名 pd.value_counts() 索引

assembly - 如何遍历汇编中的字符串,直到到达null? (strlen循环)

C++使用指针算法查找字符串长度