mirx
mirx

Reputation: 626

Find a string that matches another string on specific position, ignore other strings (C strings)

Let's say I have an array of phone numbers: char numbers[4][9] = {"555555534", "112221222", "512221222", "355555534"}; I need to find there phone numbers, that matches a specific pattern.

For example, I can find a number:

  1. 5******** that starts with a 5, and the rest of the digits can be ignored (does not matter what they're really)
  2. **2***** the third digit is 2, and the rest of the digits can be ignored (does not matter what they're really)
  3. etc.

The pattern I should look for is given by the user. I wrote a simple test, but somehow I have problems with implementing the number_matches function.

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

int main()
{
    int i,j;

    char *findmeplz = "5********";
    char numbers[4][9] = {"555555534", "112221222", "512221222", "355555534"};

    for (i=0; i<4; i++)
    {
        if(number_matches(numbers[i], findmeplz))
        {
            printf("number found on position %d\n", i);
            break;
        }
    }

    return 0;
}

Upvotes: 0

Views: 27

Answers (1)

OmG
OmG

Reputation: 18838

The function can be like the following:

int number_matches(char* number, char* pattern)
{
    int i = 0, flag = 1;
    for(i = 0; i < strlen(pattern); i++)
    {
         if(pattern[i] != '*')
         {
             if(pattern[i] != number[i])
             {
                 flag = 0;
                 break;
             }
         }
    }
    return flag;
}

Upvotes: 1

Related Questions