在我的类(class)中,我们对字符串使用字符数组。如果我要使用 if else
语句,如果我将其修改为这样做,这样的事情会起作用吗?
我知道这样的数组会将每个字符分解为简单的字母。要使用 if else
语句,我必须像 array[1] == 'H' 等等。
有没有一种方法可以修改下面的代码,以便在我输入“Alas”时吐出我想要的信息。现在,它只转到 else
部分。
int main()
{
char s[10];
printf("Yo, this is a string: ");
gets_s(s);
if (s == "Alas")
{
printf("B ");
}
else
{
printf("A");
}
system("pause");
}
最佳答案
使用 strncmp
比较两个字符串的标准库函数。包括 <string.h>
标题。
strncmp(const char *s1, const char *s2, size_t n)
返回值:
Upon successful completion,
strncmp()
shall return an integer greater than, equal to, or less than 0, if the possibly null-terminated array pointed to bys1
is greater than, equal to, or less than the possibly null-terminated array pointed to bys2
respectively.
关于c - 如何使用字符数组来识别一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21961132/