首页 > 解决方案 > 在这种情况下,strcmp 如何在 C 中工作?我有一个要循环的数组和一个需要与数组中的每个元素进行比较的字符

问题描述

我有一个名为 notes 的数组,它是

char *NOTES[] = {"A", "Bb", "B", "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab"};

然后我需要实现一个获取笔记索引的函数

int get_note_index(char* string) {}

我想到了使用 strcmp 预先编写的方法来比较传入参数的参数是字符串和 notes 数组的元素。

我做了类似strcmp(string,NOTES[i])where iis 用 for 循环递增的事情。

注意:传递的字符串本身就是一个注释,例如A输出的位置0,因为在成功比较之后NOTES[0]将与参数字符串匹配。等等1"Bb"

我是 C 新手,所以我不知道如何有效地使用strcmp()它,或者它是否可以像这样使用。

标签: carrayspointersc-stringsstrcmp

解决方案


函数声明应如下所示

size_t get_note_index( const char *a[], size_t n, const char *s ); 

也就是说,您必须传递数组中将在函数内的循环中使用的元素数。

如果未找到该字符串,则该函数返回数组最后一个元素之后的位置。

这是一个演示程序。

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

size_t get_note_index( const char *a[], size_t n, const char *s ) 
{
    size_t i = 0;

    while ( i < n && strcmp( a[i], s ) != 0 ) ++i;

    return i;
}

int main(void) 
{
    const char * NOTES[] = 
    {
        "A", "Bb", "B", "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab"
    };

    const size_t N = sizeof( NOTES ) / sizeof( *NOTES );

    const char *s = "Db";

    size_t pos = get_note_index( NOTES, N, s );

    if ( pos != N )
    {
        printf( "The index of the string \"%s\" is %zu\n", s, pos );
    }
    else
    {
        printf( "The string \"%s\" is not found\n", s );
    }

    s = "Bd";

    pos = get_note_index( NOTES, N, s );

    if ( pos != N )
    {
        printf( "The index of the string \"%s\" is %zu\n", s, pos );
    }
    else
    {
        printf( "The string \"%s\" is not found\n", s );
    }

    return 0;
}

程序输出为

The index of the string "Db" is 4
The string "Bd" is not found

推荐阅读