C++ 将字符串中的字符与给定的字符进行比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10490636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Compare between a char in a string to a given char
提问by Itzik984
I have the following:
我有以下几点:
int findPar(char* str)
{
int counter=0;
while (*str)
{
if(str[0] == "(") <---- Warning
{
counter++;
}
else if (str[0]== ")") <---- Warning
{
counter--;
}
if (counter<0)
{
return 0;
}
str++;
}
if (counter!=0)
{
return 0;
}
return 1;
}
The warning i get is comparison between an int and a char.
我得到的警告是 int 和 char 之间的比较。
I tried to do the comparison (first char in the string vs. given char) also with strcmp like this:
我也尝试使用 strcmp 进行比较(字符串中的第一个字符与给定的字符),如下所示:
if (strcmp(str, ")")==0) { stuff }
but it never goes in to 'stuff' even when the comparison (should) be correct.
但即使比较(应该)是正确的,它也永远不会进入“东西”。
how should i do it?
我该怎么做?
回答by Imp
If str
is a C string (null-terminated array of chars), then str[0]
is a char.
如果str
是 C 字符串(以空字符结尾的字符数组),则str[0]
是一个字符。
Note that the type of quotes matters! ')'
is a char, while ")"
is a string (i.e. a ')'
char followed by a null terminator).
请注意,引号的类型很重要!')'
是一个字符,")"
而是一个字符串(即一个')'
字符后跟一个空终止符)。
So, you may compare two chars:
因此,您可以比较两个字符:
str[0] == ')'
or you may compare two strings
或者你可以比较两个字符串
strcmp(str, ")") == 0
naturally, (the second works if str
string really only contains that parenthesis).
自然,(如果str
字符串真的只包含该括号,则第二个有效)。
回答by Seth Carnegie
You're comparing a character (str[0]
) with a const char[N]
("whatever"
). You need to use single quotes because double quotes denote character arrays, whereas single quotes denote single characters:
您正在将字符 ( str[0]
) 与const char[N]
( "whatever"
)进行比较。您需要使用单引号,因为双引号表示字符数组,而单引号表示单个字符:
if (str[0] == ')') // or *str == ')'
Etc.
等等。
The reason why strcmp
was failing as well was because, while the string at some time does point to the )
, it has more characters beyond that (i.e. is not followed immediately by a '\0'
) so the string is not equivalent to the string ")"
which has one character.
strcmp
失败的原因也是因为,虽然字符串在某些时候确实指向)
,但它还有更多的字符(即后面没有紧跟 a '\0'
),因此该字符串不等同于")"
具有一个字符的字符串。
回答by Daniel Fischer
Double quotes, "
are string delimiters, so ")"
is a pointer to a string literal in if(str[0] == "(")
.
You want to compare to a character, so you have to use single quotes
双引号"
是字符串分隔符,因此")"
是if(str[0] == "(")
. 你想与一个字符进行比较,所以你必须使用单引号
if(str[0] == '(')
回答by Kerrek SB
You need if (str[0] == ')')
etc. Note the single quotation marks (apostrophes) to denote character literals.
您需要if (str[0] == ')')
等。请注意单引号(撇号)表示字符文字。