黑马程序员技术交流社区

标题: 数字的处理。。。 [打印本页]

作者: 深知一生短暂    时间: 2013-9-10 17:47
标题: 数字的处理。。。
本帖最后由 深知一生短暂 于 2013-9-10 22:38 编辑

给定一串数字,如 00551332. 问 如何将数字前面的零全部去掉?前面的零是任意数目的,可有可无?
想知道大家有什么方法进行处理?用正则表达式也可以。
作者: 武嘉豪    时间: 2013-9-10 18:12
  1. class Demo2
  2. {
  3.         public static void main(String[] args)
  4.         {
  5.                 String s="00005";
  6.                 int i=Integer.valueOf(s).intValue();
  7.                 System.out.println(i);
  8.         }
  9. }
复制代码
转换成数字类型前面的0就没有了~
作者: 杨增坤    时间: 2013-9-10 18:24
这里使用的是正则表达式里面的组进行的操作!
  1. public static void main(String [] agrs){
  2.                 String str="00056";
  3.                 String regex="[0]+([1-9]+)";
  4.                 str=str.replaceAll(regex,"$1");
  5.                 System.out.println(str);
  6.         }
复制代码
希望你能理解,对你有帮助!

作者: 杨彬    时间: 2013-9-10 18:31
  1.        String str="100005145200";
  2.                 ArrayList list=new ArrayList();
  3.                 char[] ch=str.toCharArray();
  4.                 for(int i=0;i<ch.length;i++){
  5.                         char c=ch[i];
  6.                         if(c!='0'){
  7.                                 list.add(c);
  8.                         }                       
  9.                 }
  10.                 Iterator it=list.iterator();
  11.                 while(it.hasNext()){
  12.                         System.out.print(it.next());
  13.                 }
复制代码

作者: ~路@人#甲~    时间: 2013-9-10 20:08
武嘉豪 发表于 2013-9-10 18:12
转换成数字类型前面的0就没有了~

之前没有想到这方法{:soso_e183:},不过parseInt(String s)  方法更为简洁


作者: 杨彬    时间: 2013-9-10 20:39
~路@人#甲~ 发表于 2013-9-10 20:08
之前没有想到这方法,不过用parseInt(String s)  方法更为简洁

你没想过 如果开头不是以0开头呢???转换类型后 该有0还是有的!!
作者: ~路@人#甲~    时间: 2013-9-10 22:17
杨彬 发表于 2013-9-10 20:39
你没想过 如果开头不是以0开头呢???转换类型后 该有0还是有的!!

public class Demo4 {

        public static void main(String[] args) {
                String s = "0023023";
                int i = Integer.parseInt(s);
                System.out.println(i);

        }

}









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