How to reverse words in a string that has line feed (\n or \r) with C#

1 Answer

0 votes
using System;
using System.Text;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "java\n" +
                       "c\n" +
                       "php\n" +
                       "python";

            s = reverseWords(s);

            Console.WriteLine(s);
        }
        public static string reverseWords(string s)
        {
            StringBuilder sb = new StringBuilder();
            char[] sp = {'\n', '\r'};
            string[] arr = s.Split(sp);

            for (int i = arr.Length - 1; i >= 0; i--) {
                String[] words = arr[i].Split(' ');
                for (int j = words.Length - 1; j >= 0; j--) {
                    sb.Append(words[j]).Append(" ");
                }
                sb.Append("\n");
            }
            return sb.ToString();

        }
    }
}


/*
run:
        
python
php
c
java
   
*/

 



answered Jul 26, 2018 by avibootz

Related questions

4 answers 293 views
1 answer 222 views
1 answer 253 views
1 answer 180 views
1 answer 165 views
1 answer 249 views
...