1

I'm new to programming in c# and I'm trying to figure out how I could potentially reverse all words except words containing e in a string.

my current code will detect words containing e, and just writes them down in another textbox:

string text = txbInput.Text;
            var words = text.Split(' ');
            for (int i = 0; i < words.Length; i++)
            {
                if (words[i].Contains('e'))
                {
                   txbOutput.Text += words[i];
                }

Current:

Input: chicken crossing the road

Output: chickenthe

.

Expected outcome:

Input: chicken crossing the road

Output chicken gnissorc the daor

Saimoyi
  • 23
  • 4

3 Answers3

3

You can simply split the word on the space character, then, for each word, select either the word itself, or the word reversed (depending on whether or not it contains the 'e' character), and then join them back together again with the space character:

txbOutput.Text = string.Join(" ", txbInput.Text.Split(' ')
    .Select(word => word.Contains("e") ? string.Concat(word.Reverse()) : word));
Rufus L
  • 36,127
  • 5
  • 30
  • 43
1

Outputs: chicken gnissorc the daor

using System;


namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            var input = "chicken crossing the road";

            foreach (var item in input.Split(' '))
            {
                if (item.Contains('e'))
                {
                    Console.Write(item + ' ');
                }
                else
                {
                    Console.Write(Reverse(item) + ' ');
                }
            }
        }

        public static string Reverse(string s)
        {
            char[] charArray = s.ToCharArray();
            Array.Reverse(charArray);
            return new string(charArray);
        }
    }
}
enter code here

EDIT

 foreach (var item in input.Split(' '))
    {
        if (item.Contains('e'))
        {
            txbOutput.Text = txbOutput.Text+ item + ' ';
        }
        else
        {
            txbOutput.Text= txbOutput.Text+ Reverse(item) + ' ';
        }
    }
betelgeuce
  • 837
  • 5
  • 18
  • `Array.Reverse(s.ToCharArray())` [does not reverse strings](https://stackoverflow.com/questions/228038/). – Dour High Arch May 09 '19 at 22:09
  • The question starts out with "I am new to programming..". I think it is important to work with simple and understandable answers to introduce core concepts. – betelgeuce May 09 '19 at 22:16
  • What could I potentially add, in order to ignore the special characters? – Saimoyi May 16 '19 at 08:54
0

You can try using the following code -

string.Join(” “,
      str.Split(‘ ‘)
         .Select(x => new String(x.Reverse().ToArray()))
         .ToArray());

Copied from - https://www.declarecode.com/code-solutions/csharp/caprogramtoreverseeachwordinthegivenstring