1. 程式人生 > >去除字串中相鄰重複的字元

去除字串中相鄰重複的字元

public class Test{

	public static void main(String[] args) {
		String str = "aabbbccccdddddeeeeeeeeefff234tttdddfffbbbggg";
		String result = removeRepeatChar(str);
		System.out.println("去重前----:" + str);
		System.out.println("去重後----:" + result);
	}

	public static String removeRepeatChar(String s) {
		StringBuffer sb = new StringBuffer();
		int i = 0;
		while (i < s.length()) {
			char c = s.charAt(i);
			sb.append(c);
			while (i < s.length() && s.charAt(i) == c) {// 這個是如果這兩個值相等,就讓i+1取下一個元素
				i++;
			}
		}
		return sb.toString();
	}
}

原文連結