Pages

Thursday, March 28, 2013

C#: Check if one string is rotation of another string

public void StringRotate()
{
   string str = "myblogpost";  //Declare a string
   string checkstr = "tsopgolbym"; //String to be checked
   char[] charArr = new char[str.Length]; //Intialize a new char array
    int j = 0;

    if (str.Length == checkstr.Length)// if both strings are equal length
   {
    for (int i = str.Length-1; i >=0; i--) //then continue to check rotation
    {
        charArr[j] = str[i];
        j++;
    }
    string str1 = new string(charArr); // Intialize a new string
    if (str1 == checkstr)
    {
        Console.WriteLine("Both strings are rotation strings");
    }
    else
    {
        Console.WriteLine("Both strings are not a rotation strings");
    }
    }
    else // if both strings are not equal length
    {
     Console.WriteLine("Both strings are not equal length and not rotation strings");
     }
 }

Output: Both strings are rotation strings

1 comment: