/*
 * File: ReverseString.java
 * -------------------------
 * This program reverses a string.
 */

import acm.program.*;

public class ReverseString extends ConsoleProgram {
	
	public void run() {
		println("This program reverses a string.");
		String str = readLine("Enter string: ");
		
		// reverse with first approach
		String rev = reverseString(str);
		println(str + " spelled backwards is " + rev + ".");
		
		// reverse with second approach
		String rev2 = reverseStringV2(str);
		println(str + " spelled backwards is " + rev2 + ".");
	}
	
	/*
	 * reverseString
	 * -------------
	 * Returns a reversed version of the string str. Loops backwards
	 * over the original string, and keeps adding characters to the
	 * end of the result string.
	 */
	private String reverseString(String str) {
		String result = "";
		for(int i = str.length() - 1; i >= 0; i--) {
			result += str.charAt(i);
		}
		return result;
	}
	
	/*
	 * reverseStringV2
	 * ----------------
	 * A second method that also returns a reversed version of the
	 * string str. This method loops forward over the original string,
	 * and keeps adding characters to the front of the result string.
	 */
	private String reverseStringV2(String str) {
		String result = "";
		for(int i = 0; i < str.length(); i++) {
			result = str.charAt(i) + result;
		}
		return result;
	}
}