- 0
Notifications Mark All Read
No New notification
- Login
- Get Prime
Java program to check if two strings match where one string contains wildcard characters
Checking if two strings match where one string contains wildcard characters
In this article, we will learn how to write a Java program to check if two strings match where one string contains wildcard characters. Wildcard characters are those that can be compared with one or more characters. ‘*’ and ‘?’ are typical wildcard characters where ‘*’ can be compared with zero or more characters (string, str*ng,s*g are same )and ‘?’ can be compared with only one character (string, str?ng are same).
Algorithm :
- Take two input string wild and str.
- Check both strings character by character.
- If a character of wild string contains a ‘*’ , take the next character from wild string and check for that character in string which you want to match.
- If they match, continue checking the next character. Else, return false.
- If the character of wild string contains a ‘?’, check if the immediate next character of wild string and the next character of string to be matched.
- If they match, continue checking the next characters. Else, return false.
- Print the result.
Java Solution to check if two string match where one string contains wildcard character
import java.util.*; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter String containing wild Charcater"); String wild = sc.next(); System.out.println("Enter String to be matched"); String str = sc.next(); boolean flagA = true, flagB = false; int m = wild.length(), n = str.length(); boolean check[][] = new boolean[m + 1][n + 1]; check[0][0] = true; for (int i = 1; i <= n; i++) check[0][i] = false; for (int i = 1; i <= m; i++) { if (wild.charAt(i - 1) == '*') check[i][0] = check[i - 1][0]; else check[i][0] = false; } for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (wild.charAt(i - 1) == str.charAt(j - 1)) check[i][j] = check[i - 1][j - 1]; else if (wild.charAt(i - 1) == '?') check[i][j] = check[i - 1][j - 1]; else if (wild.charAt(i - 1) == '*') check[i][j] = check[i - 1][j] || check[i][j - 1]; else check[i][j] = false; } } if (check[m][n]) System.out.println("true"); else System.out.println("false"); } }
Output :
Enter string containing wild characater :
prep*nsta
Enter string to be matched :
prepinsta
true
Note
In this program, we will make a function check() with boolean as a return type, that will return true if the strings match else it will return false. This is an article on Java program to check if two strings match while one string containing wildcard characters.
Login/Signup to comment