面接問題の収集(二十二)(文字列の挿入)

1785 ワード

public class Insert {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(insert("ab def", "abc", 3));
		System.out.println(inversion("ab def"));
	}

	/**
	 *  
	 */
	public static String insert(String info, String insert, int index) {

		if (info == null || insert == null) {
			throw new NullPointerException(
					"the insert string is null or the info string is null.");
		}
	
		if (info.length() < index) {
			throw new IndexOutOfBoundsException(
					"the insert index is out of bounds.");
		}
		char[] buffer = null;
		if (info.length() == 0) {
			return insert;
		} else if (insert.length() == 0) {
			return info;
		} else {
			buffer = new char[info.length() + insert.length()];

			for (int i = 0; i < info.length(); i++) {
				if (i < index) {
					buffer[i] = info.charAt(i);
				} else {
					buffer[i + insert.length()] = info.charAt(i);
				}
			}

			for (int i = 0; i < insert.length(); i++) {
				buffer[index + i] = insert.charAt(i);
			}
		}

		return new String(buffer);
	}

	/**
	 *  
	 */
	public static String inversion(String info) {
		if (info == null) {
			throw new NullPointerException("the info string is null.");
		}
		char[] buffer = new char[info.length()];
		for (int i = 0; i < info.length(); i++) {
			buffer[i] = info.charAt(info.length() - i - 1);
		}

		return new String(buffer);
	}
}