C#剥离/转换一个或多个字符

DRa*_*app 4 c# parsing character strip

有没有一种快速的方法(无需显式循环遍历字符串中的每个字符)并剥离或保留它.在Visual FoxPro中,有一个功能CHRTRAN(),它做得很好.它以1:1的字符替换,但如果在替换位置没有字符,则将其从最终字符串中剥离.防爆

CHRTRAN("这将是一个测试","它","X")

将返回

"ThXs将成为一个es"

注意原始"i"被转换为"X",小写"t"被删除.

我看了替换类似的意图,但没有看到替换什么都没有的选项.

我正在寻找一些通用例程来验证具有不同类型输入限制的多个数据源.一些数据可能来自外部来源,因此我不仅需要测试文本框条目验证.

谢谢

Jon*_*n B 9

您只需要对String.Replace()进行几次调用即可.

string s = "This will be a test";
s = s.Replace("i", "X");
s = s.Replace("t", "");
Run Code Online (Sandbox Code Playgroud)

请注意,Replace()返回一个新字符串.它不会改变字符串本身.


Dan*_*ner 5

这是你想要的吗?

"This will be a test".Replace("i", "X").Replace("t", String.Empty)
Run Code Online (Sandbox Code Playgroud)

这是CHRTRAN函数的一个简单实现- 如果字符串包含\0并且非常混乱,它就不起作用.你可以使用循环编写一个更好的,但我只是想用LINQ尝试它.

public static String ChrTran(String input, String source, String destination)
{
    return source.Aggregate(
        input,
        (current, symbol) => current.Replace(
            symbol,
            destination.ElementAtOrDefault(source.IndexOf(symbol))),
        preResult => preResult.Replace("\0", String.Empty));
}
Run Code Online (Sandbox Code Playgroud)

你可以使用它.

// Returns "ThXs wXll be a es"
String output = ChrTran("This will be a test", "it", "X");
Run Code Online (Sandbox Code Playgroud)

只是为了得到一个干净的解决方案 - 同样没有LINQ并且也适用于\0案例,并且它几乎就位,因为使用StringBuilder但不会修改输入,当然.

public static String ChrTran(String input, String source, String destination)
{
    StringBuilder result = new StringBuilder(input);

    Int32 minLength = Math.Min(source.Length, destination.Length);

    for (Int32 i = 0; i < minLength; i++)
    {
        result.Replace(source[i], destination[i]);
    }

    for (Int32 i = minLength; i < searchPattern.Length; i++)
    {
        result.Replace(source[i].ToString(), String.Empty);
    }

    return result.ToString();
}
Run Code Online (Sandbox Code Playgroud)

缺少空引用处理.

受到tvanfosson解决方案的启发,我给了LINQ第二枪.

public static String ChrTran(String input, String source, String destination)
{
    return new String(input.
        Where(symbol =>
            !source.Contains(symbol) ||
            source.IndexOf(symbol) < destination.Length).
        Select(symbol =>
            source.Contains(symbol)
                ? destination[source.IndexOf(symbol)]
                : symbol).
        ToArray());
}
Run Code Online (Sandbox Code Playgroud)


DRa*_*app 5

这是我的最终功能,并按预期完美运行.

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;
}
Run Code Online (Sandbox Code Playgroud)