代码之家  ›  专栏  ›  技术社区  ›  DRapp

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

  •  4
  • DRapp  · 技术社区  · 17 年前

    有没有一种快速的方法(不必显式地循环字符串中的每个字符)来剥离或保留它。在VisualFoxPro中,有一个函数CHRTRAN()非常适合。它以1:1字符替换,但如果替换位置没有字符,则从最后一个字符串中删除它。前任

    会回来的

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

    我查看了replace以获得类似的目的,但没有看到一个选项可以不替换任何内容。

    我希望制作一些通用例程来验证具有不同类型输入限制的多个数据源。一些数据可能来自外部来源,所以我需要测试的不仅仅是文本框输入验证。

    谢谢

    7 回复  |  直到 17 年前
        1
  •  9
  •   Jon B    17 年前

    你只需要打几个电话给 String.Replace() .

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

    请注意,Replace() 新的字符串。它不会改变字符串本身。

        2
  •  5
  •   Daniel Brückner    17 年前

    这是你想要的吗?

    "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,同样为 因为使用了 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());
    }
    
        3
  •  5
  •   DRapp    17 年前

    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;
    }
    
        4
  •  4
  •   Robert Rossney    17 年前

    在这种情况下,我认为使用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();
    }
    
        5
  •  3
  •   Meta-Knight    17 年前

    要“替换为nothing”,只需替换为空字符串。这将为您提供:

    String str = "This will be a test";
    str = str.Replace("i", "X");
    str = str.Replace("t","");
    
        6
  •  3
  •   tvanfosson    17 年前

    作为字符串扩展名的更通用版本。与其他字符串一样,由于字符串在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();
            }
        }
    }