String slicing in C# to rotate a string

CsharpProgrammingServer Side Programming

Let’s say our string is −

var str = "welcome";

Use the substring() method and the following, if you want to rotate only some characters. Here, we are rotating only 2 characters −

var res = str.Substring(1, str.Length - 1) + str.Substring(0, 2);

The following is the complete code −

Example

 Live Demo

using System;

public class Program {
   public static void Main() {
      var str = "welcome";

      Console.WriteLine("Original String = "+str);
      var res = str.Substring(1, str.Length - 1) + str.Substring(0, 2);

      Console.WriteLine("Rotating two characters in the String: "+res);
   }
}

Output

Original String = welcome
Rotating two characters in the String: elcomewe
raja
Published on 31-Aug-2018 13:12:39
Advertisements