View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
Given two strings that can contain lower and uppercase alphabets, numbers and special characters like dots, blank spaces, commas, etc. Compare both strings considering only alphanumeric characters[[a-b], [A-B] and [0-9]] if they are equal or not. For example, strings “Ram, Shyam” and “Ram-Shyam” both are the same and also “/.’;[]” and “@# >” are same.
Examples:
Input: str1 = "Ram, Shyam", str2 = " Ram - Shyam." Output: Equal Explanation: if we ignore all characters except alphanumeric characters then strings will be, str1 = "RamShyam" and str2 = "RamShyam". Therefore both strings are equal. Input : str1 = "aaa123", str2 = "@aaa-12-3" Output : Equal Input : str1 = "abc123", str2 = "123abc" Output : Unequal Explanation: In this, str1 = "abc123" and str2 = "123abc". Therefore both strings are not equal.
Since we have to compare only alphanumeric characters therefore whenever any other character is found simply ignore it by increasing iterator pointer. For doing it simply take two integer variables i and j and initialize them by 0. Now run a loop to compare each and every character of both strings. Compare one by one if the character is alphanumeric otherwise increase the value of i or j by one.
Below is the implementation of the above approach:
C++
#include
using
namespace
std;
bool
CompareAlphanumeric[string& str1, string& str2]
{
int
i, j;
i = 0;
j = 0;
int
len1 = str1.size[];
int
len2 = str2.size[];
while
[i