Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        2年前关闭。
                                                                                            
                
        
如何反转用户输入字符串的一部分?
公正的数字不应该扭转所有其他部分必须扭转。

ABC123DEF   --> CBA123FED
DISK0123CAR --> KSID0123RAC
596ABCDEF   --> 596FEDCBA


先感谢您
这是我的代码:

public static string ReverseStr(string sStrRev)
{
        string output = "";
        Dictionary<int, char> SChar = new Dictionary<int, char>();

        int Cposition = 0;

        for (int i = sStrRev.Length - 1; i >= 0; i--)
        {
            if (sStrRev[i] != '1' && sStrRev[i] != '2' && sStrRev[i] != '3'
                && sStrRev[i] != '4' && sStrRev[i] != '5'
                && sStrRev[i] != '6' && sStrRev[i] != '7'
                && sStrRev[i] != '8' && sStrRev[i] != '9'
                && sStrRev[i] != '0')
                output += sStrRev[i];
            else
            {
                SChar.Add(Cposition, sStrRev[i]);
            }
            Cposition++;
        }

        for (int i = 0;i<sStrRev.Length ; i++)
        {
            if (SChar.ContainsKey(i))
                output.Insert(i, SChar[i].ToString());
        }
            return output;
 }

最佳答案

我建议使用正则表达式来匹配要反转的所有部分,并使用Linq来反转它们:

  using System.Linq;
  using System.Text.RegularExpressions;

  ...

  string source = "DISK0123CAR";

  // KSID0123RAC
  string result = Regex.Replace(source,
    "[^0-9]+",                                        // all except numbers ...
     match => string.Concat(match.Value.Reverse()));  // ... should be reversed


如果要将其包装到方法中:

  public static string ReverseStr(string sStrRev) {
    // when implementing public methods do not forget to validate the input
    if (string.IsNullOrEmpty(sStrRev))
      return sStrRev;

    return Regex.Replace(sStrRev,
      "[^0-9]+",
       match => string.Concat(match.Value.Reverse()));
  }


编辑:请注意,该解决方案不会交换数据块:

  ABC123DEF   --> CBA123FED    // <- CBA and FED are not swapped
  DISK0123CAR --> KSID0123RAC
  596ABCDEF   --> 596FEDCBA


如果您也想反转块的顺序

  string result = string.Concat(Regex
    .Split(source, "([^0-9]+)")
    .Reverse()
    .Select(chunk => chunk.All(c => c >= '0' && c <= '9')
       ? chunk
       : string.Concat(chunk.Reverse())));


结果将是

    ABC123DEF   --> FED123CBA    // chunks are swapped
    DISK0123CAR --> RAC0123KSID
    596ABCDEF   --> FEDCBA596

关于c# - C#中字符串的反向部分,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42501635/

10-17 01:47