简体   繁体   中英

How to remove whitespace, unwanted chars from list to compare string values c#

I have a list, lets say unknownChars which contains aa number of strings 'Unknown', 'TBC', 'TBA' etc, which are needed for user validation.

I need to check if the string entered exists within my lists, however I need to to be aware of all possibilities, such as casing, and extra character such as 'UUknown' and special characters such as N/A. I'm assuming I will need to first of all normalize the input, to remove any whites spacing and any other characters entered by mistake and then process the input to see if the nomrilised string is a match.

public bool useUnkownPack(string strTest)
{
    List<string> unkownChars = new List<string> {'Unknown', 'TBC', 'TBA', "N/A"}
    if(unkown.Contains(strTest, StringComparer.OrdinalIgnorcase))
    {
       return false;
    }
    return true;
}

So if someone could point me in the right direction how to normilise the input out any any unwanted characters before i match its I would be very grateful

Make sure your list of items has all normalised, character-only values. Then use regex to remove any non alpha characters.

Regex rgx = new Regex("[^a-zA-Z]");
Console.WriteLine(useUnkownPack(rgx.Replace(inputValue, "")));

....

public static bool useUnkownPack(string strTest)
{
    List<string> unkownChars = new List<string> {"Unknown", "TBC", "TBA", "NA"};

    if(unkownChars.Contains(strTest, StringComparer.OrdinalIgnoreCase))
    {
       return false;
    }

    return true;
}

Live example: http://rextester.com/QFCW63817

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM