Reputation: 2378
I have 2 strings which both are some kind of reference number (have a prefix and digits).
string a = "R&D123";
string b = "R&D 123";
string a
and string b
are two different user input, and I'm trying to compare if the two strings matches.
I know I can use String.Compare()
to check if two strings are the same, but like in the example above, they could be different strings but are technically the same thing.
Because they are both user inputs (from different users), there can be several different formats.
"R&D123"
"R&D 123" //with space in between
"R.D.123 " //using period or other character
"r&d123" //different case
"RD123" //no special character
...etc
Is there a way I can somehow "normalize" the two strings first then compare them??
I know a easy-to-understand way is use string.Replace()
to replace special characters and spaces to blank space and use string.ToLower()
so I don't have to worry about cases. But the problem with this method is that if I have many special characters, I'll be doing .Replace()
quite a few times and that's not ideal.
Another problem is that R&D
is not the only prefix I need to worry about, there are others such as A.P.
, K-D
, etc. Not sure if this will make a difference :/
Any help is appreciated, thanks!
Upvotes: 1
Views: 128
Reputation: 1722
This might not be the prettiest way to to do but it's the fastest
static void Main(string[] args)
{
string sampleResult = NormlizeAlphaNumeric("Hello wordl 3242348&&))&)*^&#R&#&R#)R#@)R#@R#R#@");
}
public static string NormlizeAlphaNumeric(string someValue)
{
var sb = new StringBuilder(someValue.Length);
foreach (var ch in someValue)
{
if(char.IsLetterOrDigit(ch))
{
sb.Append(ch);
}
}
return sb.ToString().ToLower();
}
Upvotes: 3
Reputation: 1587
try this...
string s2 = Regex.Replace(s, @"[^[a-zA-Z0-9]]+", String.Empty);
it will replace all the special characters and give you the normalize string.
Upvotes: 1
Reputation: 101701
If you want to just letters and digits,you can do it with linq:
var array1 = a.Where(x =>char.IsLetterOrDigit(x)).ToArray();
var array2 = b.Where(x => char.IsLetterOrDigit(x)).ToArray();
var normalizedStr1 = new String(array1).ToLower();
var normalizedStr2 = new String(array2).ToLower();
String.Compare(normalizedStr1,normalizedStr2);
Upvotes: 3