C/C++, Codes

String rotation

/*
	Programmer 	: Duc Ho
	Date		: 01/31/2012
	Object		: Write a function that take in 2 string and check if
				  one string is the rotate of the other	 
*/
#include <iostream>
#include <string>
using namespace std;

bool isRotateString(string, string);

int main()
{
	string s1,s2;
	cout << "Input string 1: ";
	cin  >> s1;
	cout << "Input string 2: ";
	cin >> s2;
	if ((isRotateString(s1,s2)) == true)
		cout << "YES!!!";
	else cout << "NO!!!";
	return 0;
}

bool isRotateString(string s1, string s2)
{
	//have to be same length at first
	if (s1.length() != s2.length())
		return false;
	//yeah same length, now what?
	else
	{
		string rString = "";
		int i, m = s1.length();
		char c;
		//starting from the very-end
		for (i = s1.length()-1; i >= 0; --i)
		{
			c = s1[i];
			if (s1[i] == toupper(c))
			{
				rString += s1.substr(i, m - i);
				m -= (m - i);
			}
		}
		
		cout << "Rotated string : " << rString << endl;

		if (rString == s2)
			return true;
		else return false;
		
	}
}		

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s