3

As you can see i use start index from arr[0] and arr.last(); but anyone can suggest another way to do the same thing more simple?


    public static string F(string s)
    {
        char[] arr = s.ToCharArray();
        Array.Reverse(arr);

        if (s.Length >= 2)
            return new string(arr)[0] + "" + arr.Last();
        else
            return s;
    }
  • On reversing strings: http://stackoverflow.com/questions/228038/best-way-to-reverse-a-string –  Mar 16 '14 at 13:01

3 Answers3

7

You can do it like this, you don't need Array.Reverse:

public static string F(string s)
{
   if (s.Length >= 2)
        return new string(new[] { s[s.Length - 1], s[0] });
    else
        return s;

}
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
5

If you take always the first and the last character of the string then the reversion is irrelevant and you can directly use the index and just swap the otput:

var input = "abcdefg";
Console.WriteLine("{1} - {0}", input[0], input[input.Length - 1]);

Output is:

g - a
keenthinker
  • 7,645
  • 2
  • 35
  • 45
1
public static string F(string s)
{
     return s.Length >= 2 ? new string(new[] { s.Last(), s.First() }) : s;
}
evilone
  • 22,410
  • 7
  • 80
  • 107