Skip to content

Instantly share code, notes, and snippets.

@VegaFromLyra
Created June 30, 2015 22:01
Show Gist options
  • Save VegaFromLyra/6b43776d0b398326d825 to your computer and use it in GitHub Desktop.
Save VegaFromLyra/6b43776d0b398326d825 to your computer and use it in GitHub Desktop.
Wild card matching
using System;
// Given two strings where first string may contain wild card characters and second string
// is a normal string. Write a function that returns true if the two strings match.
// The following are allowed wild card characters in first string
// * --> Matches with 0 or more instances of any character or set of characters.
// ? --> Matches with any one character.
namespace WildCard
{
public class Program
{
public static void Main(string[] args)
{
test("g*ks", "geeks"); // Yes
test("ge?ks*", "geeksforgeeks"); // Yes
test("g*k", "gee"); // No because 'k' is not in second
test("*pqrs", "pqrst"); // No because 't' is not in first
test("abc*bcd", "abcdhghgbcd"); // Yes
test("abc*c?d", "abcd"); // No because second must have 2 instances of 'c'
test("*c*d", "abcd"); // Yes
test("*?c*d", "abcd"); // Yes
}
static void test(string s1, string s2) {
if (Match(s1, s2)) {
Console.WriteLine("Yes");
} else {
Console.WriteLine("No");
}
}
public static bool Match(string s1, string s2) {
if (String.IsNullOrEmpty(s1) && String.IsNullOrEmpty(s2)) {
return true;
}
if (String.IsNullOrEmpty(s1) || String.IsNullOrEmpty(s2)) {
return false;
}
if (s1.Length == 1 && s1[0] == '*') {
return true;
}
if (s1[0] == '?' || s1[0] == s2[0]) {
return Match(s1.Substring(1), s2.Substring(1));
}
if (s1[0] == '*') {
return Match(s1, s2.Substring(1)) || Match(s1.Substring(1), s2);
}
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment