问题描述
对于C编程我还是很陌生,如果有的话,我如何能够检查字符串是否包含某个字符?
I'm fairly new to C programming, how would I be able to check that a string contains a certain character for instance, if we had:
void main(int argc, char* argv[]){
char checkThisLineForExclamation[20] = "Hi, I'm odd!"
int exclamationCheck;
}
因此,我如何将 exclamationCheck
设置为1(如果为!")呢?存在,如果不存在则为0?非常感谢您提供的任何帮助.
So with this, how would I set exclamationCheck
with a 1 if "!" is present and 0 if it's not? Many thanks for any assistance given.
推荐答案
通过使用 strchr(),例如:
#include <stdio.h>
#include <string.h>
int main(void)
{
char str[] = "Hi, I'm odd!";
int exclamationCheck = 0;
if(strchr(str, '!') != NULL)
{
exclamationCheck = 1;
}
printf("exclamationCheck = %d\n", exclamationCheck);
return 0;
}
输出:
如果您正在寻找一种简洁的班轮,那么您可以按照@melpomene的方法进行操作:
If you are looking for a laconic one liner, then you could follow @melpomene's approach:
int exclamationCheck = strchr(str, '!') != NULL;
如果不允许使用C字符串库中的方法,则按照@SomeProgrammerDude的建议,您可以简单地对字符串进行迭代,并且如果有任何字符是感叹号,如本示例所示:
If you are not allowed to use methods from the C String Library, then, as @SomeProgrammerDude suggested, you could simply iterate over the string, and if any character is the exclamation mark, as demonstrated in this example:
#include <stdio.h>
int main(void)
{
char str[] = "Hi, I'm odd";
int exclamationCheck = 0;
for(int i = 0; str[i] != '\0'; ++i)
{
if(str[i] == '!')
{
exclamationCheck = 1;
break;
}
}
printf("exclamationCheck = %d\n", exclamationCheck);
return 0;
}
输出:
请注意,当找到至少一个感叹号时,您可以中断循环,这样就无需遍历整个字符串.
Notice that you could break the loop when at least one exclamation mark is found, so that you don't need to iterate over the whole string.
PS: main()在C和C ++中应该返回什么? int
,而不是 void
.
这篇关于如何检查字符串是否包含某个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!