user11540908
user11540908

Reputation:

How can I compare two strings by more than just one character?

So I want to compare two strings by more than just one character. I know how to compare two strings character by character, or just by character on an selected position but I'm not sure how to compare two string by more than one character? For example I want to compare two string by 3 last characters, how can I do that?

I've tried this:

if( strcmp(str1-1, str2-1)==0 && strcmp(str1-2, str2-2) ==0)

but it doesn't work. I'm taking two strings from the user with scanf function.

if( strcmp(str1, str2) ==0){
    printf("equal");
}else{
    printf("not");

Upvotes: 1

Views: 1354

Answers (4)

hyde
hyde

Reputation: 62908

If you want to compare just certain number of chars, you can use strncmp.

If you want to compare last 3 characters, then you need to determine the index of 3rd last character of each strings, so you can start comparing from that. For that you need strlen.

Putting above together, and accounting for strings shorter than 3 chars:

int pos1 = strlen(str1) - 3;
int pos2 = strlen(str2) - 3;

if (pos1 >= 0 && pos2 >= 0 && strncmp(str1 + pos1, str2 + pos2, 3) == 0) {
   // last 3 chars of the strings match
}

Upvotes: 0

David Ranieri
David Ranieri

Reputation: 41045

There is not such function in the standard, but you can roll your own, something like:

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

int revcmp(const char *a, const char *b, size_t start)
{
    size_t len;

    len = strlen(a);
    if (len < start) {
        return 0;
    }
    a += len - start;
    len = strlen(b);
    if (len < start) {
        return 0;
    }
    b += len - start;
    return !strcmp(a, b);
}

int main(void)
{
    char *a = "abcxyz";
    char *b = "123xyz";

    printf("%d\n", revcmp(a, b, 3));
    return 0;
}

Upvotes: 1

MiCo
MiCo

Reputation: 401

First you need to determine the string length of both strings. The lengths must be bigger than the number of last characters you want compare. With pointer arithmetic you can move to the positions where you want start your comparison:

int strlen1 = strlen(str1);
int strlen2 = strlen(str2);
const int LASTCMP = 3;
if (strlen1 >= LASTCMP && strlen2 >= LASTCMP 
   && strcmp(str1+strlen1-LASTCMP , str2+strlen2-LASTCMP ) == 0)
{
    printf("last %d characters are equal", LASTCMP);
}
else
{
    printf("not");
}

Upvotes: 0

Barmar
Barmar

Reputation: 782488

You need to get the length of the strings, subtract 3 from that, and add that to the start of the string to get the index to start comparing. Also, make sure that you don't get a negative index if the length of the string is less than 3.

size_t len1 = strlen(str1);
size_t index1 = len1 >= 3 ? len1 - 3 : 0;
size_t len2 = strlen(str2);
size_t index2 = len2 >= 3 ? len2 - 3 : 0;

if (strcmp(str1 + index1, str2 + index2) == 0) {
    printf("equal\n");
} else {
    printf("not equal\n");
}

Upvotes: 4

Related Questions