替代不需要正则表达式的String.split();

阅读更多
源字符串有n个分隔符,生成的List的size就为n+1,没有内容的元素就为空串("")
	/**
	 * 分解字符串
	 * 
	 * @param source
	 * @param delimiter
	 * @return
	 */
	public static List splitByStr(String source, String delimiter) {
		ArrayList list = new ArrayList();
		if (source == null || source.length() == 0) {
			return list;
		}
		if (delimiter == null || delimiter.length() == 0) {
			list.add(source);
			return list;
		}
		int fromIndex = 0;
		int delimiterLength = delimiter.length();

		do {
			int index = source.indexOf(delimiter, fromIndex);
			if (index == fromIndex) {
				list.add("");
			} else if (index == -1) {
				list.add(source.substring(fromIndex, source.length()));
				break;
			} else {
				list.add(source.substring(fromIndex, index));
			}
			fromIndex = index + delimiterLength;
		} while (true);

		return list;
	}

你可能感兴趣的:(java,split,分割字符串)