Souza
Souza

Reputation: 1143

Check for defined characters in string input

I've been reading some stuff about C, i'm a beginner and at this point this is where i'm at:

This function keeps the input from the keyboard:

void store_sequence(char *arg) {
    strcpy(estado.seq, arg);
    estado.tamanho = strlen(arg);
}

and this is what i came so far to check if there are As on the string that was inserted on the keyboard:

void sequence_does_contain_As_and_Bs(char *arg) {

  char buf [] = estado.seq;

  s = strchr (buf, 'A');

  if (s != NULL)
    printf ("found a 'A' at %s\n", s);

}

So, basically, i need to detect if the input string has only As and Bs

Upvotes: 0

Views: 64

Answers (2)

niculare
niculare

Reputation: 3687

Try this:

char buf [] = estado.seq;
int len = estado.tamanho;
int i;
int contains = 1;
for (i = 0; i < len; ++i)
    if (buf[i] != 'A' && buf[i] != 'B') {
        contains = 0;
        break;
    }
if (contains)
  // do whatever you want if the string contains only As and Bs

Upvotes: 1

SpacedMonkey
SpacedMonkey

Reputation: 2773

Have a look at this - http://www.cplusplus.com/reference/cstring/

Particularly strspn() and strcspn()

Upvotes: 2

Related Questions