C# Stripping / converting one or more characters

2019-02-18 05:52发布

Is there a fast way (without having to explicitly looping through each character in a string) and either stripping or keeping it. In Visual FoxPro, there is a function CHRTRAN() that does it great. Its on a 1:1 character replacement, but if no character in the alternate position, its stripped from the final string. Ex

CHRTRAN( "This will be a test", "it", "X" )

will return

"ThXs wXll be a es"

Notice the original "i" is converted to "X", and lower case "t" is stripped out.

I looked at the replace for similar intent, but did not see an option to replace with nothing.

I'm looking to make some generic routines to validate multiple origins of data that have different types of input restrictions. Some of the data may be coming from external sources, so its not just textbox entry validation I need to test for.

Thanks

7条回答
迷人小祖宗
2楼-- · 2019-02-18 06:15

  public static string ChrTran(string cSearchIn, string cSearchFor, string cReplaceWith)
        {
            string result = "";
            dynamic inArray = cSearchIn.ToCharArray();
            foreach (var caracter in inArray)
            {
                int position = cSearchFor.IndexOf(caracter);
                result = result + cReplaceWith.Substring(position, 1);

} return result; }</pre>
查看更多
登录 后发表回答