黑马程序员技术交流社区

标题: 字符串中去除字符串空格的问题 [打印本页]

作者: yjgoss    时间: 2014-1-7 20:45
标题: 字符串中去除字符串空格的问题
class StringTest
{
        public static void main(String[] args)
        {
                String s = "  abcde  ";
                         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);
        }
}
怎么编译都是好多错误,请大家看看我哪里写错了,是字符串除去空格的
作者: 马富林    时间: 2014-1-7 21:39
楼主的代码有点看不懂,自己写了个,试了下,结果可行,仅供楼主参考
  1. public class Test {

  2.         public static void main(String[] args) {
  3.                 String str="      abc    ";
  4.                 System.out.println(myTrim(str));
  5.         }
  6.         public static String myTrim(String str){
  7.                 while(str.startsWith(" ")){
  8.                         str=str.substring(1);
  9.                 }
  10.                
  11.                 while(str.endsWith(" ")){
  12.                         str=str.substring(0, str.length()-1);
  13.                 }
  14.                 return str;
  15.         }
  16. }
复制代码

作者: 松毛    时间: 2014-1-7 21:58
  1. public class Test12
  2. {
  3.         public static void main(String[] args)
  4.         {
  5.                 String s = "  abcde    ";
  6.                          s = myTrim(s);
  7.                 System.out.println(s);
  8.         }
  9.         //去除字符串丙端的空格
  10.         public static String myTrim(String str)
  11.         {
  12.            int start = 0,end = str.length()-1;
  13.            
  14.            while(start<=end && str.charAt(start)==' ')//这里是空格;
  15.                    start++;
  16.            while(start<=end && str.charAt(end)==' ')
  17.                    end--;
  18.               return str.substring(start,end+1);  //这里的substring写错了s小写
  19.         }
  20. }
复制代码

作者: 午夜b'Boy    时间: 2014-1-7 22:17
while(start<=end && str.charAt(end)=='')这里str.charAt(end)=="空格",估计少空格
作者: yjgoss    时间: 2014-1-7 22:39
松毛 发表于 2014-1-7 21:58

弄对了,非常的感谢




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