user9822308
user9822308

Reputation:

Reverse Words at odd position only C#

This is my code. How can I edit it to show every word which is at the odd position ONLY to be reversed?

        for (int i = input.Length - 1; i >= 0; i--)
        {
            if (input[i] == ' ')
            {
                result =  tmp + " " + result;
                tmp = "";
            }
            else
                tmp += input[i];
        }

        result = tmp + " " + result;
        Console.WriteLine(result);

Example input:

"How are you today"

to output:

"How era you yadot"

Based on the position of a word ['How' -> 0] do not reverse; [are -> 1 odd index] Reverse

Upvotes: 1

Views: 1445

Answers (4)

Sagar Jadhav
Sagar Jadhav

Reputation: 129

try this is perfect working code..

 static void Main(string[] args)
    {
        string orgstr = "my name is sagar";
        string revstr = "";
        foreach (var word in orgstr.Split(' '))
        {
            string temp = "";
            foreach (var ch in word.ToCharArray())
            {
                temp = ch + temp;
            }
            revstr = revstr + temp + " ";
        }

        Console.Write(revstr);
        Console.ReadKey();
    }

Output: ym eman si ragas

Upvotes: 0

DirtyBit
DirtyBit

Reputation: 16772

OP: Based on the position of a word ['How' -> 0] do not reverse; [are -> 1 odd index] Reverse

public static void Main()
{
    string input = "How are you today Laken-C";

     //As pointed out by @Dmitry Bychenko string input = "How are you today";
    //(double space after How) leads to How are uoy today outcome 

    input = Regex.Replace(input, @"\s+", " ");
    var inp = input.Split(' ').ToList();

    for (int j = 0; j < inp.Count(); j++)
    {   
       if(j % 2 == 1)
       {
           Console.Write(inp[j].Reverse().ToArray());
           Console.Write(" ");
       }
       else
           Console.Write(inp[j] + " ");
    }
}

OUTPUT:

enter image description here

DEMO:

dotNetFiddle

Upvotes: 3

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186698

So far you have a string, like this:

  string input = "I want to reverse all odd words (odd words only!).";

And you, naturally, want to perform the task. Now it's the main question what's an odd word? If you mean word's position (I at position 0, want at 1 - should be reversed etc.) then you can use regular expressions to match words and Linq to process them:

  using System.Linq;                     // To reverse single word
  using System.Text.RegularExpressions;  // To match the words within the text

  ... 

  // Let's elaborate the test example: add
  //  1. some punctuation - ()!. - to preserve it 
  //  2. different white spaces (spaces and tabulation - \t)
  //     to add difficulties for naive algorithms
  //  3. double spaces (after "to") to mislead split based algorithms
  string input = "I want to  reverse all\todd words (odd words only!).";

  int index = 0;                                // words' indexes start from zero

  string result = Regex.Replace(
    input,
   "[A-Za-z']+",                                // word is letters and apostrophes
    match => index++ % 2 == 0 
      ? match.Value                             // Even words intact
      : string.Concat(match.Value.Reverse()));  // Odd words reversed

  Console.WriteLine(result);

If you want to reverse the words with odd Length, i.e. I, all, odd then all you have to do is to change the condition to

    match => match.Value % 2 == 0 

Outcome:

  I tnaw to  esrever all    ddo words (ddo words ylno!).

Please, notice, that the punctuation has been preserved (only words are reversed).

Upvotes: 4

ProgrammingLlama
ProgrammingLlama

Reputation: 38767

You can achieve it with the help of LINQ:

var input = "hello this is a test message";
var inputWords = input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var result = string.Join(" ", 
                 inputWords.Select((w, i) => 
                                         i % 2 == 0
                                         ? w 
                                         : new string(w.Reverse().ToArray())
                 ));

Where w in the select is the word, and i is the index, starting at 0 for the first word. % is the modulus operator and gets the remainder. If i % 2 == 0 (i.e. i can be divided by 2 with no remainder), then the original is returned. If there is a remainder (odd) then the reversed word is returned. Finally, it's all wrapped up in a string.Join(" ", items); which turns it back into a normal string rather than an array of items.

Try it online

Upvotes: 4

Related Questions