在这种情况下,strcmp在C中是如何工作的?我有一个要循环的数组和一个需要与数组中的每个元素进行比较的char



我有一个名为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])的操作,其中i通过for循环递增。

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

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

函数声明应该看起来像

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 %zun", s, pos );
}
else
{
printf( "The string "%s" is not foundn", s );
}
s = "Bd";
pos = get_note_index( NOTES, N, s );
if ( pos != N )
{
printf( "The index of the string "%s" is %zun", s, pos );
}
else
{
printf( "The string "%s" is not foundn", s );
}
return 0;
}

程序输出为

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

您的解决方案将类似于:

int get_note_index(char* string) {
for (int i = 0; i < 12; i++) {
if (strcmp(string, NOTES[i]) == 0) {
return i;
}
}
return -1; // not found
}

您可能需要将12替换为音调行大小的#define。如果音符不匹配,我在这里返回-1。

最新更新