user3648443
user3648443

Reputation: 5

how can i find two substrings

I can find a substring with using strstr function. For example I can find "Hello" substring, but I want to find "Hello" and "welcome". Not only one of them I want to find both of them. I want to think about "hello" and "welcome" like they are the same word. If the program can find the world "hello" it returns false, if the program can find the world "welcome" it returns false but if the program can find the words "hello" and "welcome" it returns true. how can I do that?

int main(){

int total=0;
char *p="Hello world welcome!";
   while ( strstr(p,"Hello") != NULL ) {
      printf("%s", p); // to know the content of p
      p++;
      total++;
   }
 printf("%i", total);
 getch(); // pause
}

Upvotes: 0

Views: 95

Answers (3)

BLUEPIXY
BLUEPIXY

Reputation: 40145

int main(){
    char *p="Hello world welcome!";
    printf("%i", strstr(p, "Hello") && strstr(p, "welcome"));
    return 0;
}

Upvotes: 0

macfij
macfij

Reputation: 3209

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

char find_two(char* p, const char* first, const char* sec) {
    char* t1 = strstr(p, first);
    char* t2 = strstr(p, sec);
    if (t1 != NULL && t2 != NULL) {
        return 1;
    }
    else {
        return 0;
    }
}

int main(void)
{
    char* p = "hello world welcome";
    printf("%d\n", find_two(p, "hello", "welcome"));
    printf("%d\n", find_two("hello i am xx", "hello", "welcome"));
    printf("%d\n", find_two("welcome i am xx", "hello", "welcome"));
    printf("%d\n", find_two("testing abc", "hello", "welcome"));

    return 0;
}

output:

1
0
0
0

EDIT:

Some different implementation of find_two (as suggested by @Jongware) :

char find_two(char* p, const char* first, const char* sec) {
    char *t1, *t2;
    if ((t1 = strstr(p, first)) == NULL) {
        return 0;
    }
    if ((t2 = strstr(p, sec)) == NULL) {
        return 0;
    }
    return 1;
}

Upvotes: 2

Matthias
Matthias

Reputation: 3556

You are a bit unclear about the problem description. What is the realtionhseip between hte two substrings? Are they connected? like "Hello welcome"? Even though your codes lets one conclude that you want to count occurences this is not explicitly stated in your question. In general you can use the strstr function as often as you want. Two count two strings - why should you not do:

int total_hello=0;
int total_welcome=0;
char *p="Hello world welcome!";
char *p_1=p;
char *p_2=p;
while ( strstr(p_1,"Hello") != NULL ) {
   printf("%s", p_1); // to know the content of p
   p_1++;
   total_hello++;
}
while ( strstr(p_2,"welcome") != NULL) {
    printf("%s", p_2);
    p_2++;
    total_welcome++;
}
return total_hello > 0 && total_welcome>0;

to count hellos and welomces?

Note that i have created copies of the original "char* p" variable and feed that as a parameter into the strstr function.

Upvotes: 0

Related Questions