收集面试题(五)(截取字符串,不允许出现半位)

截取字符串,不允许出现半个的,例如123卡3,截取4位是123
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String info = "1234か5sss";

		System.out.println(subString(info, 6));
	}

	public static String subString(String strInfo, int subLength) {

		if (strInfo == null) {
			throw new IndexOutOfBoundsException("string is null.");
		}

		int strLength = strInfo.length();
		int strByteLength = strInfo.getBytes().length;

		if (strLength == strByteLength) {
			return strInfo.substring(0, subLength);
		} else {

			byte[] buffer = new byte[subLength];
			byte[] bytes = strInfo.getBytes();
			for (int i = 0; i < subLength; i++) {
				if (i > bytes.length) {
					break;
				}
				buffer[i] = bytes[i];
			}
			if (new String(buffer).equals(strInfo.substring(0, subLength))) {
				return strInfo.substring(0, subLength);
			} else {
				return strInfo.substring(0, subLength - 1);
			}
		}

	}

你可能感兴趣的:(面试)