实现JAVA中String.trim()方法

 实现一个简单的String.trim(String s)方法(清除一个字符串两边空格)。

public class Term {

	public String trim1(String s) {
		char[] cArray = s.toCharArray();
		int index = 0;
		for (int i = 0; i < cArray.length; i++) {
			if (cArray[i] != ' ') {
				index = i;
				break;
			}
		}
		char[] tArray1 = new char[cArray.length - index];
		for (int i = 0; i < cArray.length; i++) {
			if (index + i < cArray.length) {
				tArray1[i] = cArray[index + i];
			}
		}
		for (int i = tArray1.length - 1; i >=0; i--) {
			if (tArray1[i] != ' ') {
				index = i;
				break;
			}
		}
		char[] tArray = new char[index + 1];
		for (int i = 0; i < index + 1; i++) {
			tArray[i] = tArray1[i];
		}
		return new String(tArray);
	}
	
	public String trim2(String s) {
		StringBuffer sfr = new StringBuffer(s);
		int c = 0;
		for (int i = 0; i <sfr.length(); i++) {
			if (sfr.charAt(i) != ' ') {
				if (c > 0) {
					sfr.delete(0, i);
					sfr.reverse();
					return sfr.toString();
				}
				sfr.delete(0, i);
				i = 0;
				c += 1;
				sfr.reverse();
			}
		}
		return s;
	}
	
	public static void main(String[] args) {
		Term term = new Term();
		System.out.println(term.trim1("   ab c b   "));
		System.out.println(term.trim2("   ab c b   "));
	}
}

 输出结果为:

ab c b
ab c b
 

你可能感兴趣的:(java,C++,c,C#)