4

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

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

将返回

“ThXs wXll be a es”

注意原来的“i”被转换成“X”,小写的“t”被去掉了。

我查看了类似意图的替换,但没有看到任何替换的选项。

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

谢谢

4

6 回答 6

9

您只需要几次调用String.Replace()

string s = "This will be a test";
s = s.Replace("i", "X");
s = s.Replace("t", "");

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

于 2009-05-11T17:56:44.493 回答
5

这是你想要的吗?

"This will be a test".Replace("i", "X").Replace("t", String.Empty)

这是该函数的一个简单实现- 如果字符串包含并且非常混乱,则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));
}

你可以使用它。

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

只是为了有一个干净的解决方案 - 在没有 LINQ 的情况下也一样,并且也适用于这些案例,并且由于使用 a但不会修改输入,\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();
}

缺少空引用处理。

受到 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());
}
于 2009-05-11T17:59:11.023 回答
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;
}
于 2009-05-13T01:47:51.023 回答
4

在这种情况下,我认为使用 LINQ 会使事情变得过于复杂。这很简单,也很重要:

private static string Translate(string input, string from, string to)
{
    StringBuilder sb = new StringBuilder();
    foreach (char ch in input)
    {
        int i = from.IndexOf(ch);
        if (from.IndexOf(ch) < 0)
        {
            sb.Append(ch);
        }
        else
        {
            if (i >= 0 && i < to.Length)
            {
                sb.Append(to[i]);
            }
        }
    }
    return sb.ToString();
}
于 2009-05-11T19:38:26.387 回答
3

要“替换为空”,只需替换为空字符串即可。这会给你:

String str = "This will be a test";
str = str.Replace("i", "X");
str = str.Replace("t","");
于 2009-05-11T17:59:11.680 回答
3

作为字符串扩展的更通用的版本。像其他人一样,这不会进行适当的翻译,因为字符串在 C# 中是不可变的,而是返回一个带有指定替换的新字符串。

public static class StringExtensions
{
    public static string Translate( this string source, string from, string to )
    {
        if (string.IsNullOrEmpty( source ) || string.IsNullOrEmpty( from ))
        {
            return source;
        }

        return string.Join( "", source.ToCharArray()
                                   .Select( c => Translate( c, from, to ) )
                                   .Where( c => c != null )
                                   .ToArray() );
    }

    private static string Translate( char c, string from, string to )
    {
        int i = from != null ? from.IndexOf( c ) : -1;
        if (i >= 0)
        {
            return (to != null && to.Length > i)
                      ? to[i].ToString()
                      : null;
        }
        else
        {
            return c.ToString();
        }
    }
}
于 2009-05-11T18:20:51.473 回答