Search code examples
c#parsingcharacterstrip

C# Stripping / converting one or more characters


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


Solution

  • Here was my final function and works perfectly as expected.

    public static String ChrTran(String ToBeCleaned, 
                                 String ChangeThese, 
                                 String IntoThese)
    {
       String CurRepl = String.Empty;
       for (int lnI = 0; lnI < ChangeThese.Length; lnI++)
       {
          if (lnI < IntoThese.Length)
             CurRepl = IntoThese.Substring(lnI, 1);
          else
             CurRepl = String.Empty;
    
          ToBeCleaned = ToBeCleaned.Replace(ChangeThese.Substring(lnI, 1), CurRepl);
       }
       return ToBeCleaned;
    }