String小练习1-模拟一个trim方法

来源:互联网 发布:ubuntu kylin垃圾 编辑:程序博客网 时间:2024/06/12 01:29

模拟一个trim方法,去除字符串两端的空格。

思路:

  • 1.判断字符串第一个位置是否是空格,如果是继续向下判断,直到不是空格为止。
    结尾处判断空格也是如此。
  • 2.当开始和结尾都判断到不是空格时,就是要获取的字符串。

public class StringDemo02 {    public static void main(String[] args) {        String s ="  ad cf    ";        System.out.println("s="+s+"-----------");        s = myTrim(s);        System.out.println("s="+s);    }    //去除字符串两端空格    public static String myTrim(String str){        int start = 0,end = str.length()-1;        while(start<=end && str.charAt(start)==' ')            start++;        while(start<=end && str.charAt(end)==' ')            end--;        return str.substring(start,end+1);    }}
0 0
原创粉丝点击