How to Rotate/Shift characters of string to left for given number of times

Guru_Navale
Posted by Guru_Navale under C# category on | Points: 40 | Views : 3844
Below methods take the number n which tells how many times you want to shift/rotate the string. I have taken the MOD by length of string if the number is greater than the length of string.


namespace StringOperations
{
class Program
{
static void Main(string[] args)
{
string str = "ABCDEF";
try
{
Rotate(ref str, 3);

Console.WriteLine(str);
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}

str = "ABCDEF";
try
{
Rotate1(ref str, 3);

Console.WriteLine(str);
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}


}

public static void Rotate(ref string str, int n)
{
if (n < 1)
throw new Exception("Negative number for rotation"); ;
if (str.Length < 1) throw new Exception("0 length string");

if (n > str.Length)
{
n = n % str.Length;
}

StringBuilder s1=new StringBuilder(str.Substring(n,(str.Length - n)));
s1.Append(str.Substring(0,n));
str=s1.ToString();

}

public static void Rotate1(ref string str, int n)
{
if (n < 1)
throw new Exception("Negative number for rotation"); ;
if (str.Length < 1) throw new Exception("0 length string");

if (n > str.Length)
{
n = n % str.Length;
}

str = String.Concat(str.Skip(n).Concat(str.Take(n)));
}


}
}

Comments or Responses

Login to post response