String slicing in C# to rotate a string


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

Updated on: 22-Jun-2020

297 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements