3

I would like to reverse each word from input.txt using c# and linq and display the output text, so far i have a code that inputs the word and reverses it.

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

namespace program
{
    class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("String:");
            string name = Console.ReadLine();

            string output = new string(name.ToCharArray().Reverse().ToArray());

            Console.WriteLine(output);
        }
    }
}
  • Could you please show an example input and output? Do you want to reverse every string a file? – Soner Gönül Mar 17 '14 at 12:47
  • 1
    input : I love programming output : I evol gnimmargorp – user3215507 Mar 17 '14 at 12:47
  • possible duplicate of [Easy way to reverse each word in a sentence](http://stackoverflow.com/questions/5391198/easy-way-to-reverse-each-word-in-a-sentence) – Soner Gönül Mar 17 '14 at 12:48
  • 2
    Could you clarify whether you want to reverse the whole thing or pieces within it, i.e. a string or the word(s) in a string? If the string is "one two three" would the correct result be "eerht owt eno" or "three two one"? – Rick Davin Mar 17 '14 at 12:50
  • You're converting the entire string to an char array. Try splitting it into an array of strings (words delimited by blanks), then reverse that string. – Rick Davin Mar 17 '14 at 12:51

2 Answers2

4
string input = "I love programming";
string output = String.Join(" ",
                   input.Split().Select(w => new String(w.Reverse().ToArray())));
// I evol gnimmargorp

Reading file is simple:

string input = File.ReadAllText("input.txt");

You can also move word reversing into separate method. That will allow you to change algorithm of string reversing without touching other logic:

private static string GetReversedString(string s)
{
    return new String(s.Reverse().ToArray());
}

And getting reversed output will look like:

string output = String.Join(" ", input.Split().Select(GetReversedString));

If lines should be preserved:

string output = 
    String.Join(Environment.NewLine, 
                File.ReadLines().Select(l => 
                       String.Join(" ", l.Split().Select(GetReversedString))));
Community
  • 1
  • 1
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
0

The reversal code could be refactored in an extension method for String; Next, a text file should be opened, the lines splitted to single words and the words mapped reversely to the console.

Codor
  • 17,447
  • 9
  • 29
  • 56