ratzip
ratzip

Reputation: 1671

how to compare some part of a string in c?

I have a question about compare only some part of a string

For example:

char *string = "nameOfPeople_Allen";

char searchName[20] = "Allen";

how to trim the char *string = "nameOfPeople_Allen";from _ to get the name Allen, then compare it with searchName, I know how to compare string, but how to get the last part of the "nameOfPeople_Allen" from _?

Upvotes: 2

Views: 1537

Answers (5)

haccks
haccks

Reputation: 106112

Use strstr standard library function.

char *temp = strstr(string, "Allen"); 

then use strcmp to compare it with searchName.

To find the sub-string after - use strchr

char *temp = strchr(string, '_');   
if(temp)  
    printf("%s\n", temp+1);

Upvotes: 3

Hynek -Pichi- Vychodil
Hynek -Pichi- Vychodil

Reputation: 26131

The simple and fast way:

// static inline if you are interested
int sameName(const char *string, const char *searchName) {
    const char *p;
    return (p = strchr(string, '_')) && strcmp(p+1, searchName) == 0;
}

Upvotes: 1

moffeltje
moffeltje

Reputation: 4669

if you would like to loop trough it for some reason, try this:

int i, check = 0, position = 0;
char part_of_string[20];
for(i = 0; i < strlen(string); i++){
    if(check){ 
         part_of_string[position] = string[i];
         position++;
    }else if(string[i] == '_'){
         check = 1;
    }
}

Now part_of_string contains the chars after the '_' character. You could compare it with strcmp() or loop through it again to check for "Alan".

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234875

As for trimming, whatever you do, don't modify string as it is allocated in read-only memory. (You can help yourself here by using const char* string)

But you can use strstr to check for containment:

if (strstr(string, "Allen"))...

Upvotes: 0

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53026

Just use strchr()

char *pointer;
if ((pointer = strchr(string, '_')) != NULL)
 {
    printf("The text after _ is %s\n", pointer + 1);
 }

Upvotes: 3

Related Questions