我如何计算结构中的 char 字符串?

How can i count a char string in a struct?

有没有办法计算一个名字在结构中出现了多少次?

这基本上就是我想要做的:创建一个程序来确定名称在列表中出现的次数。

用户将输入一个出现的名字,然后输出是输入的名字在列表中出现的次数。

#include<stdio.h>

typedef struct Person {
    char name[50];
} Person;

void print_people(const Person *people) {
    for (size_t i = 0; people[i].name[0]; ++i)
        printf("%-20s \n", people[i].name);
}

int main() {

    Person people[] = { {"Alan"}, {"Bob"}, {"Alan"}, {"Carol"}, {"Bob"}, {"Alan"} };
    print_people(people);
    char name;

    return 0;

}

您可能需要这样的功能:

int count_person(const Person *people,const Person who) {
    int whocount = 0;

    for (size_t i = 0; people[i].name[0]; ++i)
        if (strcmp(people[i].name,who.name) == 0)
            whocount++;
    return whocount;
}

首先,您的函数 print_people 有一个错误。行

for (size_t i = 0; people[i].name[0]; ++i)

错了。它会越界读取数组,因为循环条件 people[i].name[0] 是错误的。仅当数组由 name[0] 设置为 '[=18=]' 的元素终止时,此循环条件才会正确。在你的问题 original version 中是这种情况,但在你当前的版本中不是。

因此,您应该将该行更改为以下内容:

for (size_t i = 0; i < 6; ++i)

为了统计某个名字的人数,你所要做的就是像你在函数print_people中那样遍历数组并统计次数你遇到了你要搜索的名字:

int count_person( const Person *people, const char *target ) {

    int count = 0;

    for ( int i = 0; i < 6; i++ )
        if ( strcmp( people[i].name, target ) == 0 )
            count++;

    return count;
}

您的整个程序将如下所示:

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

typedef struct Person {
    char name[50];
} Person;

void print_people(const Person *people) {
    for (size_t i = 0; i < 6; ++i)
        printf("%-20s \n", people[i].name);
}

int count_person( const Person *people, const char *target ) {

    int count = 0;

    for ( int i = 0; i < 6; i++ )
        if ( strcmp( people[i].name, target ) == 0 )
            count++;

    return count;
}

int main() {

    Person people[] = { {"Alan"}, {"Bob"}, {"Alan"}, {"Carol"}, {"Bob"}, {"Alan"} };

    printf( "Number of occurances of \"Alan\": %d\n", count_person( people, "Alan" ) );

    return 0;
}

这个程序有以下输出:

Number of occurances of "Alan": 3