Shifting a String in C#

user2104751 picture user2104751 · Feb 24, 2013 · Viewed 20.1k times · Source
  static void Main(string[] args)
  {
     string s = "ABCDEFGH";
     string newS = ShiftString(s);
     Console.WriteLine(newS);
  }
  public static string ShiftString(string t)
  {
     char[] c = t.ToCharArray();
     char save = c[0];
     for (int i = 0; i < c.Length; i++)
     {
        if (c[i] != c[0])
        c[i] = c[i - 1];
     }
     Console.WriteLine(c);
     String s = new string(c);
     return s;
  }

I need to shift the string s one space to the left, so i end up with the string: "BCDEFGHA" So i thought about changing the string into a char array and work my way from there, but im not sure how to succesfully make this work. I'm pretty certain i need a for loop, but i need some help on how to shift the char sequence one space to the left.

Answer

John Woo picture John Woo · Feb 24, 2013

how about this?

public static string ShiftString(string t)
{
    return t.Substring(1, t.Length - 1) + t.Substring(0, 1); 
}