在这种情况下,strcmp在C中是如何工作的?我有一个要循环的数组和一个需要与数组中的每个元素进行比较的字符
我有一个名为notes的数组在这种情况下,strcmp在C中是如何工作的?我有一个要循环的数组和一个需要与数组中的每个元素进行比较的字符,c,arrays,pointers,c-strings,strcmp,C,Arrays,Pointers,C Strings,Strcmp,我有一个名为notes的数组 char *NOTES[] = {"A", "Bb", "B", "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab"}; 然后我需要实现一个函数来获取notes索引 int get_note_index(char* string) {} 我考虑使用strcmp pre-write方法来比较传入参数string的参数和notes数组的元素 我做了类似于strcmp(string,NOTES[I])的事情,其中I用for循
char *NOTES[] = {"A", "Bb", "B", "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab"};
然后我需要实现一个函数来获取notes索引
int get_note_index(char* string) {}
我考虑使用strcmp pre-write方法来比较传入参数string的参数和notes数组的元素
我做了类似于strcmp(string,NOTES[I])的事情,其中I
用for循环递增
注意:传递的字符串本身就是一个注释,例如a
,其中输出为0
,因为成功比较后NOTES[0]
将与参数字符串匹配<代码>1用于“Bb”
等
我是C新手,所以我不知道如何有效地使用strcmp(),或者它是否可以像这样使用。您的解决方案类似于:
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
}
int get\u note\u索引(char*string){
对于(int i=0;i<12;i++){
if(strcmp(字符串,注释[i])==0){
返回i;
}
}
return-1;//找不到
}
您可能希望将12替换为#定义音调行的大小。如果注释不匹配,我在这里返回-1。函数声明应该如下所示
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;
}
欢迎光临!“我做了一些类似于strcmp(string,NOTES[I])”的事情,请向我们展示确切的东西,并告诉我们您的确切输出是什么,以及它与您的预期输出有何不同。请读一下,我刚打好这个。它打印出从strcmp返回的内容。你的代码是什么样子的?@jiveturkey你的链接断了。我看到了。古怪的现在试试。你用的是什么语言?是C++还是C?如果是C,标签应该是C,而不是C++标签。注意:我读到了下一个C规范将促进<代码> siZetht n,const char * [] /代码>超过代码> const char *[],sisivit n< /代码>。也许是为了支持弗拉的签名。这个答案不是问题,但看起来是未来的趋势。
The index of the string "Db" is 4
The string "Bd" is not found