Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
String slicing in C# to rotate a string
String slicing in C# allows you to rotate characters within a string by combining substrings. This technique uses the Substring() method to extract portions of a string and rearrange them to achieve the desired rotation effect.
String rotation involves moving characters from one position to another within the string. For example, rotating the first two characters of "welcome" to the end results in "lcomewe".
Syntax
Following is the syntax for the Substring() method −
string.Substring(startIndex, length)
For string rotation, combine two substrings −
string rotated = str.Substring(n) + str.Substring(0, n);
Parameters
- startIndex − The zero-based starting character position.
- length − The number of characters to extract (optional).
- n − Number of characters to rotate from the beginning.
Using Substring() for Left Rotation
Example
using System;
public class Program {
public static void Main() {
var str = "welcome";
Console.WriteLine("Original String = " + str);
var res = str.Substring(2) + str.Substring(0, 2);
Console.WriteLine("Rotating two characters in the String: " + res);
}
}
The output of the above code is −
Original String = welcome Rotating two characters in the String: lcomewe
Using Substring() for Right Rotation
Example
using System;
public class Program {
public static void Main() {
var str = "welcome";
int rotateBy = 3;
Console.WriteLine("Original String = " + str);
// Right rotation: move last 3 characters to front
var rightRotated = str.Substring(str.Length - rotateBy) + str.Substring(0, str.Length - rotateBy);
Console.WriteLine("Right rotation by 3: " + rightRotated);
// Left rotation: move first 3 characters to end
var leftRotated = str.Substring(rotateBy) + str.Substring(0, rotateBy);
Console.WriteLine("Left rotation by 3: " + leftRotated);
}
}
The output of the above code is −
Original String = welcome Right rotation by 3: omewelc Left rotation by 3: comewe
Creating a Reusable Rotation Method
Example
using System;
public class Program {
public static string RotateLeft(string str, int positions) {
if (string.IsNullOrEmpty(str) || positions string length
return str.Substring(positions) + str.Substring(0, positions);
}
public static string RotateRight(string str, int positions) {
if (string.IsNullOrEmpty(str) || positions
The output of the above code is −
Original: programming
Left rotate by 4: ramming
Right rotate by 4: mingprog
Conclusion
String slicing in C# using the Substring() method provides an efficient way to rotate characters within a string. By combining substrings from different positions, you can achieve both left and right rotations for various string manipulation tasks.
