字符串以换行符结尾的 strcmp
strcmp with string ending with newline
我正在尝试编写一个 C 列表过滤函数,该函数接收国家/地区字符串,遍历列表并删除具有 node->country == country
的所有节点。问题是 node->country
字符串以 '\n'
结尾(因为它是从 csv 文件中读取的),因此 strcmp(node->country, country)
永远不会等于零。
我该如何解决这个问题?我首先考虑将 '\n'
附加到国家,但这可能会引发更多的内存问题。也考虑过 strstr
但我真的不知道如何处理它。
感谢您的任何建议。
当您使用 strcmp
时,让我们假设一些 C 风格的代码:
node->country[strcspn(node->country, "\n")] = '[=10=]';
这将改变您的 node->country
值并在新行(如果有)之前终止您的字符串。
建议的备选方案:
预计算
size_t len_of_country = strlen(country)
并使用
(strncmp(country, node->country, len_of_country) == 0 &&
(node->country[len_of_country] == '\n' ||
node->country[len_of_country] == '[=11=]'))
作为匹配标准。
与(1.)相同,但如果是后一种情况,还要将node->country[len_of_country]
设置为0以备后用。
- 让您的 CSV 解析器在从文件中读取国家/地区字符串时截断结尾的换行符,并且只需使用
strcmp()
.
我正在尝试编写一个 C 列表过滤函数,该函数接收国家/地区字符串,遍历列表并删除具有 node->country == country
的所有节点。问题是 node->country
字符串以 '\n'
结尾(因为它是从 csv 文件中读取的),因此 strcmp(node->country, country)
永远不会等于零。
我该如何解决这个问题?我首先考虑将 '\n'
附加到国家,但这可能会引发更多的内存问题。也考虑过 strstr
但我真的不知道如何处理它。
感谢您的任何建议。
当您使用 strcmp
时,让我们假设一些 C 风格的代码:
node->country[strcspn(node->country, "\n")] = '[=10=]';
这将改变您的 node->country
值并在新行(如果有)之前终止您的字符串。
建议的备选方案:
预计算
size_t len_of_country = strlen(country)
并使用
(strncmp(country, node->country, len_of_country) == 0 && (node->country[len_of_country] == '\n' || node->country[len_of_country] == '[=11=]'))
作为匹配标准。
与(1.)相同,但如果是后一种情况,还要将
node->country[len_of_country]
设置为0以备后用。- 让您的 CSV 解析器在从文件中读取国家/地区字符串时截断结尾的换行符,并且只需使用
strcmp()
.