/* Lecture code 3.0
 *
 * C string manipulation examples.  Some of the code here
 * is not directly from the lecture due to time issues, but
 * should be a great way to play around with the material.
 */
#include <iostream>
#include <cstring> // For string manipulation functions
using namespace std;

/**
 * Returns a substring of the source string running consisting
 * of characters in the range [start, start + length).
 * @param cString The string to extract a substring from.
 * @param start The start index to extract from
 * @param length The maximum number of characters to read
 * @return A substring, which must be freed by delete [].
 */
char *GetSubstring(char *cString, int start, int length)
{
	/* Allocate enough space for the string.  Don't
	 * forget space for the terminating null!
	 */
	char *result = new char[length + 1];
	
	/* Because strncpy doesn't automatically append a null
	 * character all of the time, manually add the null
	 * char at the end of the string.
	 */
	result[length] = '\0';
	
	/* Copy the substring.  Note that we use pointer
	 * arithmetic to advance forward start characters.
	 */
	strncpy(result, cString + start, length);
	
	return result;
}

const char *const MY_STRING = "PIRATE";

int main()
{
	/* Get a copy of MY_STRING so that we can manipulate
	 * it without causing a segmentation fault.
	 */
	char *myCString = new char[strlen(MY_STRING) + 1];
	strcpy(myCString, MY_STRING);
	
	/* Change the string to "FIXATE" */
	myCString[0] = 'F';
	myCString[2] = 'X';
	
	/* Compare the string against FIXATE. */
	if(strcmp(myCString, "FIXATE") == 0)
		cout << "Yay!  Equal strings!" << endl;
	else
		cout << "I just lost my job..." << endl;
	
	/* Print out the string length. */
	cout << "Length: " << strlen(myCString) << endl;
	
	/* Search for the character X. */
	char *xPos = strchr(myCString, 'X');
	if(xPos != NULL)
		cout << "Found X at position " << (xPos - myCString) << endl;
	else
		cout << "Didn't find X." << endl;
	
	/* Search for the string XAT. */
	char *xPos = strstr(myCString, "XAT");
	if(xPos != NULL)
		cout << "Found XAT at position " << (xPos - myCString) << endl;
	else
		cout << "Didn't find XAT." << endl;
	
	/* We're done!  Clean up. */
	delete [] myCString;
	return 0;
}
