Compare String Elements in C

Asked

Viewed 767 times

3

I would like to separate a word and compare each element of the string with a letter, I tried to make this comparison using the strcmp() but when executed seems to ignore it, or does not perform.

When I remove the condition the function separates the word normally but I cannot store the letter or compare it.

#include <string.h>
#include <stdio.h>

int main() {

  char str[20];
  gets(str);
  int i;
  int strLength = strlen(str);

  for (i = 0; i < strLength; i++) {

      if (strcmp(str[i],"c") == 0)
      {
        printf("Achei");
      }

      printf("[%c]", str[i]);

  }
}
  • 1

    If you want to compare a certain position of your string with a character use: if (str[i] == 'c')&#xA; {&#xA; printf("Achei");&#xA; }

2 answers

5


I’ll give you a few things to learn how to code correctly:

  • Do not use gets(), this function is problematic and is considered obsolete. fgets() is the correct path. I protected the memory access by taking only as many characters as possible in the reserved area as there is terminator.
  • Variables must be declared in the smallest possible scope, so the variable of the for should be stated on itself, do not use a code pattern that was used 30 or 40 years ago due to compiler failure.
  • Don’t take the size of string with strlen(), in C is very inefficient because it makes a loop, and you are already making a loop, just test whether you have reached the end, because you do not need to know the size of it.
  • When you take an element from a string is picking up a character, so you should compare it to another character, not to a string. The function you used is required to compare strings (internally has a bond in it).
  • This may be a case to do so because it is exercise, but know that it has a function ready and efficient (although being a tie was thought to be the best possible), is the strchr().

See how it gets simpler and readable:

#include <stdio.h>

int main() {
    char str[20];
    fgets(str, 19, stdin);
    for (int i = 0; str[i]; i++) {
        if (str[i] == 'c') printf("Achei");
        printf("[%c]", str[i]);
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

1

William, the problem is you’re using the function strcmp to compare one character to another, when its use, in fact, must be the comparison between strings.

In this case, therefore, you compare directly, without using the function. Your code looks like this:

#include <string.h>
#include <stdio.h>

int main() {

char str[20];
gets(str);
int i;
int strLength = strlen(str);

for (i = 0; i < strLength; i++) {

  if (str[i] == 'c')
  {
    printf("Achei");
  }

  printf("[%c]", str[i]);

 }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.