黑马程序员技术交流社区

标题: 还是去除字符串两端空格的问题 [打印本页]

作者: 张金龙    时间: 2015-3-25 10:01
标题: 还是去除字符串两端空格的问题
上个帖子里,请教了大家去除字符串两端的空格为什么不能用startsWith() endsWith(),感谢 温大帅 和 殷俊 的热情回答。之后我按照老毕讲的方法重新敲了一遍还是运行不了。希望大神帮忙解答下。谢谢!
public class StringTest {
        public static void main(String[]args){
                String s ="   kk jkl   ";
                System.out.println("("+s+")");
                s = myTrim(s);
                System.out.println("("+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);
        }
}

运行结果是
(   kk jkl   )
(   kk jkl   )

已解决。
解决办法:
while(start<=end&&str.charAt(start)!=' ')
                        start++;
                while(start<=end&&str.charAt(end)!=' ')
                        end--;
这几句有问题,应该是查到空字符时自增或自减,
while(start<=end&&str.charAt(start)==' ')
                        start++;
                while(start<=end&&str.charAt(end)==' ')
                        end--;




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2