1. 程式人生 > >java 中去除字串中的空格,兩種方法

java 中去除字串中的空格,兩種方法

/**
 * 去除字串中的所有空格
 * @author Administrator
 *
 */
public class StringTo {
	public static void main(String[] args) {
		/**
		 * 第一種方法 StringTokenizer
		 */
		String text = " we are student ";
		StringTokenizer st = new StringTokenizer(text, " ");
		StringBuffer sb = new StringBuffer();
		int i = 1;
		while (st.hasMoreTokens()) {
			i++;
			sb.append(st.nextToken());
		}
		System.out.println("第一種方法去掉空格的字串:" + sb.toString());

		System.out.println("-----------------------華麗的分隔線---------------------------------");

		/**
		 * 第二種方法 採用replaceAll
		 */

		String text2 = " j a v     a 是 個 好 語 言 ";
		text2 = text2.replaceAll(" ", "");
		System.out.println("第二種方法去掉空格的字串:" + text2);
	}
}