Home > Back-end >  How to check if string contains two words in c?
How to check if string contains two words in c?

Time:06-09

I want to make a validation in c where the user has to input a string that must be 2 words. Initially, I thought of using strstr(input, " "), to check for a space in the input but I figured that the user could put the space at the beginning and the end of the string, and they could also put more than one space resulting in more than 2 words. Does anyone have an easy solution for this? Thanks in advance!

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

int main(){
   int input;
   do{
      printf("Enter 2 words: ");
      scanf(%[^\n], input); getchar();
   }while(!strstr(input, " "));
   return 0;
}

CodePudding user response:

You could use strtok and use space as the delimiter.

CodePudding user response:

I think I managed to find a solution for this, if anyone knows a shorter way of doing this feel free to tell me.

  1. the input must only have one space.

  2. the space cannot be in the beginning or at the end of the input.

    #include <stdio.h>
    #include <string.h>
    
    int main(){
       char input[50];
       int len, ctr;
       do{
          printf("Enter 2 words: ");
          scanf(%[^\n], input); getchar();
          len = strlen(input);
          ctr = 0;
          for(int i = 0; i < len; i  ){
             if(input[i] == ' ') ctr  ;
          }
       }while(input[0] == ' ' || ctr != 1 || input[len-1] == ' ');
    
       return 0;
    }
    

Can anyone tell me if this code is ok?

CodePudding user response:

The following function returns the number of words in a (NULL terminated) string given a delimiter:

int word_count(char *str, char delimiter)
{
    int i = 0;

    if (!str || !*str)
        return (0);
    if (*str != delimiter && *(str))
        i = 1;
    while (*(str   1))
    {
        if (*str == delimiter
            && *(str   1) != delimiter
            && *(str   1))
        {
            i  ;
        }
        str  ;
    }
    return (i);
}

The logic behind it is it counts words each time the char sequence changes from a delimiter to a non \0 char, starting the number of words at 1 in case the string is not NULL and the first char is not a delimiter.
Susbtitute delimiter for ' ' and pass your scanned string to it.

  • Related