【问题标题】:reverse words in a string in c# keeping number of whitespaces same在c#中反转字符串中的单词,保持空格数相同
【发布时间】:2015-04-28 06:12:06
【问题描述】:

我正在尝试编写一个函数来反转 C# 中字符串中的单词, 例如:“这是一些文本,你好世界”
应该像这样打印 “world hello, text some is This” 反向字符串中的空格数必须相同,并且逗号等特殊字符必须正确放置在前面的单词之后,如反向字符串所示。 我试过关注,但它没有处理像','这样的特殊字符

public static string reverseStr(string s)
{
    string result = "";
    string word = "";
    foreach (char c in s)
    {
        if (c == ' ')
        {
            result = word + ' ' + result;
          word= "";
        }
         else
        {
            word = word + c;
        }
    }
    result = word + ' ' + result;
    return result;


}

【问题讨论】:

  • 你一定遇到了编译错误,因为没有string.empty,它是string.Empty(注意E)。
  • 好吧,我没有完全复制粘贴,现在编辑了
  • 这会给你什么结果(输出)?
  • “正确”放置是什么意思?您是否知道 unicode 中有不应反转的多码序列?在一般情况下,反转 unicode 字符串并不是一件容易的事。对于本地化的情况,比如只有英文文本而没有这样的“奇怪的”unicode 代码点,这很容易。例如,使用正确的字符,字符串"aè" 将反转为"eà",因为它实际上类似于"a<put an accent on the next character>e"

标签: c# string


【解决方案1】:

什么意思

带有逗号等特殊字符

还有其他需要区别对待的字符吗?这会将"This is some text, hello world" 转换为您的预期结果"world hello, text some is This"

string input = "This is some text, hello world";
string result = string.Join(" ", input.Split(' ', ',').Reverse()).Replace("  ", ", ");

更新

如果你想处理每个特殊字符,你需要一个正则表达式解决方案。

string result2 =string.Join(string.Empty,  System.Text.RegularExpressions.Regex.Split(input, @"([^\w]+)").Reverse());

【讨论】:

  • string.Join(string.Empty, 可能是string.Concat
【解决方案2】:

这是一个使用正则表达式的解决方案:

Regex.Replace(
        string.Join("",         //3. Join reversed elements
            Regex.Split(input, @"(\s+)|(,)")   //1. Split by space and comma, keep delimeters
                .Reverse()),    //2. Reverse splitted elements
@"(\s+),", @",$1");         //4. Fix comma position in joined string

【讨论】:

    【解决方案3】:

    以下解决方案保留所有空格。
    它首先检测任何字符的种类(分隔符与单词/内容)并存储块列表(其中每个项目包含开始和结束索引,以及一个布尔值,说明该块是否包含分隔符或单词)。
    然后它将块以相反的顺序写入结果字符串。

    保留每个块内的字符顺序,将块作为分隔符或单词/内容:这也允许保留任何双空格或其他分隔符链,而无需事后检查它们的顺序或数量。

    public static string Reverse(string text, Func<char, bool> separatorPredicate)
    {
        // Get all chars from source text
        var aTextChars = text.ToCharArray();
    
        // Find the start and end position of every chunk
        var aChunks = new List<Tuple<int, int, bool>>();
        {
            var bLast = false;
            var ixStart = 0;
            // Loops all characters
            for (int ixChar = 0; ixChar < aTextChars.Length; ixChar++)
            {
                var ch = aTextChars[ixChar];
                // Current char is a separator?
                var bNow = separatorPredicate(ch);
                // Current char kind (separator/word) is different from previous
                if ((ixChar > 0) && (bNow != bLast))
                {
                    aChunks.Add(Tuple.Create(ixStart, ixChar - 1, bLast));
                    ixStart = ixChar;
                    bLast = bNow;
                }
            }
            // Add remaining chars
            aChunks.Add(Tuple.Create(ixStart, aTextChars.Length - 1, bLast));
        }
    
        var result = new StringBuilder();
        // Loops all chunks in reverse order
        for (int ixChunk = aChunks.Count - 1; ixChunk >= 0; ixChunk--)
        {
            var chunk = aChunks[ixChunk];
            result.Append(text.Substring(chunk.Item1, chunk.Item2 - chunk.Item1 + 1));
        }
    
        return result.ToString();
    }
    public static string Reverse(string text, char[] separators)
    {
        return Reverse(text, ch => Array.IndexOf(separators, ch) >= 0);
    }
    public static string ReverseByPunctuation(string text)
    {
        return Reverse(text, new[] { ' ', '\t', '.', ',', ';', ':' });
    }
    public static string ReverseWords(string text)
    {
        return Reverse(text, ch => !char.IsLetterOrDigit(ch));
    }
    

    有4种方法:

    • Reverse(string text, Func separatorPredicate) 接收源文本和一个委托以确定字符何时是分隔符。
    • Reverse(string text, char[] separators) 接收源文本和要作为分隔符处理的字符数组(任何其他字符都是单词/内容)。
    • ReverseByPunctuation(string text) 仅接收源文本并将计算委托给传递一组预定义分隔符的第一个重载。
    • ReverseWords(string text) 仅接收源文本并将计算委托给第一个重载,传递一个将非字母或数字的所有内容识别为分隔符的委托。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-13
      相关资源
      最近更新 更多