We help IT Professionals succeed at work.

How to know if string contains string?

2,406 Views
Last Modified: 2013-12-14
Hi, I know this is a trivial task, but i have been googling now for over a half hour and my head is starting to spin, all I need to do is find out if this string contains this string....

char * a;
char * b;
char * target;

if(target contains a)

else if (target contains b)

any ideas?
Comment
Watch Question

Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
ozo
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
ok, this is what I have

char * i = strstr("bleh blah test/1.1.2", "test");
strncpy(i,"test",4);

and i is ending up equaliing "test/1.1.2"

how can I find out if the string begins with test?

Commented:
you can use strncmp()
if(!strncmp(str,"test",4))
 return true;

Open in new window

Author

Commented:
erm, I am not getting the results I would expect, here is my direct code...


#include <stdio.h>
#include <string.h>
 
int main(int argc,char** argv) {
 
        char * qs;
        qs = "quick section title";
 
        char * bt;
        bt = "the student was not in class today.";
 
        char * i = strstr(bt, "student");
        strncpy(i,"student",7);
 
        char * i2 = strstr(bt, "home");
        strncpy(i2,"home",4);
 
        printf("Content: test\r\n");
 
        if(!strncmp(i,"student",7))
        {
                printf("student");
        }
        else if(!strncmp(i2,"home",4))
        {
                printf("home");
        }
 
        printf(bt);
 
        fflush(0);
return 0;
}

Open in new window

ozo
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015

Commented:
What are the results you would expect?
        bt = "the student was not in class today.";
        char * i = strstr(bt, "student");
        strncpy(i,"student",7);
a constant string is not required to be writeable

        char * i2 = strstr(bt, "home");
        strncpy(i2,"home",4);
trying to write to a null pointer is undefined behavior
CERTIFIED EXPERT
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.