Java基础--Char字符除去字符串两边空格

class TrimFonction 
{
	private static final char CHARS = ' ';//记录空格常量
	public static void main(String[] args) 
	{
		String time = "   ejpo ijimlo      ";
		
		int s = 0;
		int e = time.length()-1;
		while(s < time.length() && time.charAt(s) == CHARS){ //用charAt方法,指定角标看是否有‘ ’
			s++;
		}
		while (s <= e && time.charAt(e) == CHARS){ //开始位置<=结尾位置,反则就可能有‘ ’
			e--;
		}
		String ot = time.substring(s,e+1);
		System.out.print(ot);
		System.out.print("--");//区分下结尾是否有空格
	}
}

显示结果:

ejpo ijimlo------

上面方法和String类中的trim()是相通的,平时开发建议使用trim()。

public char charAt(int index)
        返回指定索引处的  char  值。索引范围为从  0  到  length() - 1 。序列的第一个  char  值位于索引  0  处,第二个位于索引  1  处,依此类推,这类似于数组索引。
如果索引指定的
  char  值是代理项,则返回代理项值。

实例:
"ad c   ".charAt(int index ) ==ch
参数:
        index  -  charAt  值的索引。
返回:
        此字符串指定索引处的  char  值。第一个  char  值位于索引  0  处。
抛出:
      IndexOutOfBoundsException  - 如果  index  参数为负或小于此字符串的长度。


猜你喜欢

转载自blog.csdn.net/u013251413/article/details/80539919