c - 在这种情况下,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 i
is 用 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 %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
推荐阅读
- java - PdfBox - 更改矩形中的字体颜色
- python - 为了运行 Python Selenium 和访问网站的元素,你需要实际的浏览器吗?
- gnuplot - 在 gunplot 中合并具有相同比例的绘图
- android - 如何了解我必须在 Android 中的每种情况下使用哪个上下文?
- oauth-2.0 - OAuthlib 的 HTTPS 验证是什么?
- javascript - 是否可以以编程方式创建报表或将报表链接到 Azure 数据存储
- php - Symfony - 第一次使用 dotrine 后 PROD 崩溃 - 错误:无法访问私有属性 PhpFilesAdapter::$appendOnly
- kubernetes - Kubernetes 中的远程 EJB
- c - 为什么在我的代码中创建链表会产生分段错误?
- python - 如何编译 TF 运算符