/**
 * WordManipulator has several methods for dealing with Strings.
 *
 * @author Philip M. White
 */
public class WordManipulator {
	/**
	 * This method lowercases a string if case_sensitive is false.
	 * @param s	The input string to be considered for lowercasing
	 * @param case_sensitive	If true, s is unchanged; otherwise it is lowercased.
	 * @return The possibly-lowercased string is returned.
	 */
	public static String fixCase(String s, boolean case_sensitive) {
		if (case_sensitive)
			return s;
		else
			return s.toLowerCase();
	}

	/**
	 * This method strips a word of undesirable characters from beginning and end.
	 * It is similar to String.trim(), but it is more strict.
	 * @param word	The word to be stripped.
	 * @param allow_digits	Whether digits can occur at the beginning or end.
	 * @return The stripped word is returned.
	 */
	public static String strip(String word, boolean allow_digits) {
		int i;
		
		// strip the left side
		i = 0;
		while (
			/* the word has at least one character */
			!word.isEmpty() &&
			/* our index is within bounds */
			i < word.length() &&
			/* the character is not lowercase */
			!(word.charAt(i) >= 'a' && word.charAt(i) <= 'z') &&
			/* the character is not uppercase */
			!(word.charAt(i) >= 'A' && word.charAt(i) <= 'Z') &&
			/* the character is not a digit or digits are not allowed */
			!((word.charAt(i) >= '0' && word.charAt(i) <= '9') && allow_digits)) {
			i++;
		}
		if (i >= word.length())
			return "";
		word = word.substring(i);

		// now strip the right side
		i = word.length()-1;
		while (
			/* the word has at least one character */
			!word.isEmpty() &&
			/* our index is within bounds */
			i < word.length() &&
			/* the character is not lowercase */
			!(word.charAt(i) >= 'a' && word.charAt(i) <= 'z') &&
			/* the character is not uppercase */
			!(word.charAt(i) >= 'A' && word.charAt(i) <= 'Z') &&
			/* the character is not a digit or digits are not allowed */
			!((word.charAt(i) >= '0' && word.charAt(i) <= '9') && allow_digits)) {
			i--;
		}
		if (i < 0)
			return "";
		word = word.substring(0, i+1);
		return word;
	}
}
