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

xiaoxiao2023-03-19  61

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); } }

 

转载请注明原文地址: https://www.6miu.com/read-4986622.html

最新回复(0)