2

I want to parse a string and do some checks on the last character of the string. For example:

char *name = "angela";

int i;
for(i = 0; i <= strlen(name); i++) {
    if(name[i] == 'a' && i == strlen(name)) {
        *do something here*;
     }
}

I tried this but nothing happens. Why won't this work?

4

3 回答 3

10

Change:

for(i = 0; i <= strlen(name); i++) {
    if(name[i] == 'a' && i == strlen(name)) {

to:

for(i = 0; i < strlen(name); i++) {
    if(name[i] == 'a' && i == strlen(name) - 1) {

Reason: the first character in a C string, s, has index 0, and the last character has index strlen(s) - 1, for a total of strlen(s) characters.

于 2013-04-23T20:05:01.830 回答
3

您可以像这样检查字符串的最后一个字符(无需使用循环):

char *name = "angela";
if(strlen(name)>0)//do the check below only if the string is not empty
if(name[strlen(name)-1]=='a')
{
    //do something here
}
于 2013-04-23T20:22:10.127 回答
3

函数 strlen 返回一个字符串的实际长度,而不是它的最后一个索引。在您的示例“angela”中,strlen 将返回 6,但此字符数组的最后一个索引是 5。所以您必须使用:

if(name[i] == 'a' && i == strlen(name) -1)
于 2013-04-23T20:08:58.673 回答