如何在 C 中创建"X"终止字符串?



我正在尝试创建一个计数器,用于计算字符串中在";。我在使用strcmp终止while循环时遇到了问题,最终导致分段错误。这是我的:

void printAmount(const char *s)
{
int i = 0;
while ( strcmp(&s[i], "?") != 0 ) {
i++;
}
printf("%i", i);
}

不要为此使用strcmp。只需直接在s上使用下标运算符。

示例:

#include <stdio.h>
void printAmount(const char *s) {
int i = 0;
while (s[i] != '?' && s[i] != '') {
i++;
}
printf("%d", i);
}
int main() {
printAmount("Hello?world"); // prints 5
}

或使用strchr

#include <string.h>
void printAmount(const char *s) {
char *f = strchr(s, '?');
if (f) {
printf("%td", f - s);
}
}

strcmp()比较字符串,而不是字符。所以,如果您的输入类似于"123?456",那么您的逻辑就不起作用,因为"?" != "?456"。因此,while循环永远不会终止,并且开始使用字符串之外的东西。

void printAmount(const char * s) {
int i = 0;
for (; s[i] != '?' && s[i] != ''; i++) {
/* empty */
}
if (s[i] == '?') {
printf("%d",i); // the correct formatting string for integer is %d not %i
}  
}

除非您有非常奇怪或专门的需求,否则正确的解决方案是:

#include <string.h>
char* result = strchr(str, '?');
if(result == NULL) { /* error handling */ }
int characters_before = (int)(result - str);

最新更新