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
    Not related to your problem, but you should call strlen() outside the loop and store its value in a variable. It's iterating over the entire string on each call. Commented Apr 23, 2013 at 20:08
  • store the value of strlen() instead of processing it every iteration. Commented Apr 23, 2013 at 20:09
  • Since name isn't volatile (and isn't getting modified in the loop), it's probable that the calls are all getting optimized down to a single call anyways. Commented Apr 23, 2013 at 20:22
  • @BrianKnoblauch: Perhaps. I don't know how good optimizers are determining loop invariants. Commented Apr 23, 2013 at 20:30

3 Answers 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Also a fix for for: for(i = 0; i < strlen(name); i++)
3

The function strlen returns the actual length of a string, not its last index. In your example "angela", strlen will return 6 but the last index of this character array is 5. So you have to use:

if(name[i] == 'a' && i == strlen(name) -1)

Comments

3

You can just check the last character of the string like this(no need to use a loop):

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.