Inverse words in a string except punctuation

Given the line "hello there, compiler.", How can I cancel every word except punctuation. Therefore, after this is completed, it will be printed: "olleh ereht, relipmoc". instead of "olleh, ereht.relipmoc"

My code (which ignores punctuation):

 static string ReverseString(string s)
        {
            StringBuilder sb = new StringBuilder();
            string[] words = s.Split(' ');

            foreach (var word in words)
            {
                for (int i = word.Length - 1; i >= 0; i--)
                {
                    sb.Append(word[i]);
                }
                sb.Append(" ");
            }

            return sb.ToString();
        }
+4
source share
2 answers

I suggest Split(trick: not only for spaces, but also for non-word characters - space, comma, period, etc.), modification and final Concat:

  using using System.Text.RegularExpressions;

  ...

  string source = @"hello there, compiler.";

  string result = string.Concat(Regex
    .Split(source, @"(\W+)") // split on not word letter, separator preserved
    .Select(letter => letter.Length > 0 && char.IsLetter(letter[0]) 
       ? string.Concat(letter.Reverse()) // reverse letter
       : letter));                       // keep separator intact 

  Console.Write(result);

Result:

  olleh ereht, relipmoc.
+6
source

, . , , , , . ,

static string ReverseString(string s)
    {
        var sb = new StringBuilder();
        var words = s.Split(' ');

        foreach (var word in words)
        {
            var toAdd = new char();
            for (var i = word.Length -1; i >= 0; i--)
            {
                if (char.IsPunctuation(word[i]))
                {
                    toAdd = word[i];
                }
                else
                {
                    sb.Append(word[i]);
                }
            }
            if (toAdd != new char())
            {
                sb.Append(toAdd);
            }

            sb.Append(" ");
        }

        return sb.ToString();
    }

: :

static string ReverseString(string s)
    {
        var sb = new StringBuilder();

        foreach (var s1 in s.Split(' '))
        {
            var rev = s1.Reverse().ToList();
            char punct;
            if (char.IsPunctuation(punct = rev.First()))
            {
                rev.RemoveAt(0);
                rev.Add(punct);
            }
            rev.Add(' ');
            sb.Append(rev.ToArray());
        }
        return sb.ToString();
    }
+1

Source: https://habr.com/ru/post/1681359/


All Articles