`
zeyuphoenix
  • 浏览: 56010 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

收集面试题(二十二)(插入字符串)

阅读更多
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);
	}
}

 

分享到:
评论
发表评论

文章已被作者锁定,不允许评论。

相关推荐

Global site tag (gtag.js) - Google Analytics