Check if two strings match where one string contains wildcard characters

07 January 2023

Check if two strings match where one string contains wildcard characters



If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023

Description

Get two strings as input from the user, first with wildcard characters (* and ?) and second without wildcard characters. Then check whether they match or not.

 

Input

Ta**nt

Talent

Output

Yes they match

 

C Program

#include<stdio.h>

#include<stdbool.h>

bool checking(char *s1, char * s2)

{

    if (*s1 == '\0' && *s2 == '\0')

         return true;

    if (*s1 == '*' && *(s1+1) != '\0' && *s2 == '\0')

         return false;

    if (*s1 == '?' || *s1 == *s2)

         return checking(s1+1, s2+1);

    if (*s1 == '*')

         return checking(s1+1, s2) || checking(s1, s2+1);

     return false;

}

void testing(char *s1, char *s2)

{

    checking(s1, s2)? puts(" Yes "): puts(" No ");

}

int main()

{

    char s1[20],s2[20];

    printf("Enter first string with wild characters: ");

    scanf("%s",s1);

    printf("Enter second string without wild characters: ");

    scanf("%s",s2);

    testing(s1,s2);

    return 0;

}

 

C++ Program

#include<iostream>

#include<stdbool.h>

using namespace std;

bool checking(char *s1, char * s2)

{

    if (*s1 == '\0' && *s2 == '\0')

         return true;

    if (*s1 == '*' && *(s1+1) != '\0' && *s2 == '\0')

         return false;

    if (*s1 == '?' || *s1 == *s2)

         return checking(s1+1, s2+1);

    if (*s1 == '*')

         return checking(s1+1, s2) || checking(s1, s2+1);

     return false;

}

void testing(char *s1, char *s2)

{

    checking(s1, s2)? puts(" Yes "): puts(" No ");

}

int main()

{

    char s1[20],s2[20];

    cout<<"Enter first string with wild characters: ";

    cin>>s1;

    cout<<"Enter second string without wild characters: ";

    cin>>s2;

    testing(s1,s2);

    return 0;

}

 

Python Program

def solve(str1,str2):

    a,b=len(str1),len(str2)

    if a==0 and b==0:

        return True

    if (a > 1 and str1[0] == '*') and b == 0:

        return False

    if (a > 1 and str1[0] == '?') or (a != 0 and b !=0 and str1[0] == str2[0]):

        return solve(str1[1:],str2[1:]);

    if a !=0 and str1[0] == '*':

        return solve(str1[1:],str2) or solve(str1,str2[1:])

    return False

str1=input('Enter string with wild characters: ')

str2=input('Enter string without wild characters: ')

if (solve(str1,str2)):

    print("Yes it matches")

else:

    print("No it is not matching")


If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023

Related Articles

Ask Us Anything !