有一个例如 String a="000108" 的字符串,它的位数不是固定的,想要的结果是把前几个为0的字符全部去掉,结果为a="108"。用什么算法才能实现?

解决方案 »

  1.   

    什么算法也不用,正则就可以做到了 String a = "015800";
    System.out.println(a.replaceAll("^0+", ""));
      

  2.   


     String a = "000108";
     int leng = a.length();
     int j = 0 ;
     for(int i = 0 ; i < leng ; i ++){
      
      if(integer.valueOf(a.valueOf(i)).intValue() > 0)
      {
        j= i ;
      }
      Syetem.out.println(a.substring(j,leng - 1 - j)); 
         
    不知道正确不,边上没有编译工具,大概就是从前面字符开始,依次和0比较,如果大于0的话,记下它的位置,然后用substring截取~
      

  3.   

    用正则表达式,二楼的答案是最简答的String str = "000108";
    String rtnStr = str.replaceAll("^0+", "");
      

  4.   

    非常感谢了,正则表达式果然历害。但用第二种方法,有些问题如下:class  Test
    {
        public static void main(String[] args) 
        {
      //String b = "00015800";
              //System.out.println(b.replaceAll("^0+", "")); String a = "000108";
            int leng = a.length();
            int j = 0 ;
      try{
           for(int i = 0 ; i < leng ; i ++){
    if(Integer.valueOf(a.valueOf(i)).intValue() > 0)
    {
       j= i ;
    }
    System.out.println(a.substring(j,leng - 1 - j)); 
    }
      }catch(Exception e){  
      }
        }
    }
    //这样取出的结果为 如果不加try的话报 StringIndexOutOfBoundsException异常
    //00010
    //001
    //0//而不是108.
      

  5.   

    public class TextDemo
    {
    public static void main(String agrs[])
    {
    String s="00010208";
    int n=0,m=0;
    for(int i=0;i<s.length();i++)//从开始第一个不等于0的索引
    {
    if(s.charAt(i)!='0')
    {
    n=i;
    break;
    }
    }
    for(int j=s.length()-1;j>=0;j--)//从最后第一个不等于0的索引
    {
    if(s.charAt(j)!='0')
    {
    m=j;
    break;
    }
    }
    String str=s.substring(n,m+1);
    System.out.println(str);

    }}
    比较容易懂的方法!!
      

  6.   

    呵呵,如果是全是0-9组成,可以考虑转成数字再转字符串, String.valueOf(new Integer("000108"))之类,但要注意一下Integer的范围,别超出了被截断
    不然最好还是用正则表达式吧,楼主可以看看这方面的介绍
    "000108" .replaceAll("^0+", "");
      

  7.   

    while(true){
        if(str.startsWith("0")){
            str = str.substring(1);
        }
        else{
            break;
        }
    }