Home > front end >  How do you use an if else and check for last character '\0' of a string?
How do you use an if else and check for last character '\0' of a string?

Time:10-29

In C apparently strings are stored like an array with a null value or '\0' at the end. I wish to iterate over the string in a for loop and I need it to stop at '\0', not including it. I've tried many conditions for the if else and it all don't seem to work.

for example:

char patternInput[TEXTSIZE];

for(int i = 0; i<strlen(patternInput);i  )
{
    if(patternInput[i]==NULL)
    {
        printf("\nlast character");
        break;
    }
    else
    {
        printf("\n%c",patternInput[i]);
    }
}

I've tried if(patternInput[i]==NULL), if(patternInput[i]==NUL),if(!patternInput[i]),if(patternInput[i]=='\0') and none of them seems to work.

CodePudding user response:

If you're scanning the characters yourself, you can avoid the (redundant and somewhat expensive) strlen() call entirely, and instead use the value of patternInput[i] in the continuation-test of your for-loop:

char patternInput[TEXTSIZE] = "testing!";

for(int i = 0; patternInput[i] != '\0'; i  )
{
   printf("\n%c",patternInput[i]);
}
printf("\nlast character\n");

CodePudding user response:

Consider this code. This code prints 'Null character found' with position of the character. Notice the 'less than or equal to' in i<=strlen(str) in the loop invariant.

The last character at the length strlen 1 is the '\0' character.

int i = 0;
    
char str[] = "Hello";
    
for(int i=0; i<=strlen(str); i  )
{
    if(str[i]=='\0')
        printf("Null character found at position %d", i);
}
  •  Tags:  
  • c
  • Related