将字符串2,4,5,6,7,8,10,12,14,15,16转换为2,4-8,10,12,14-16

时间:2012-04-26 06:22:09

标签: java arrays string integer

我想使用java将字符串输入转换为2,3,6,7,8,10,12,14,15,16到2-3,6-8,10,12,14-16

我尝试使用以下代码

        Vector ar=new Vector();

        int lastadded=0;

        String ht="";

        String [] strarray=str.split(",");

        strarray=sortArray(strarray);

        Vector intarray=new Vector();


        for(int i=0;i<strarray.length;i++)
        {

        int temp=1;
            for(int j=1;j<=intarray.size();j++)
            {
                if(Integer.parseInt(strarray[i])==Integer.parseInt(intarray.get(j-1).toString()))
                {
                 temp=0;
                }
            }
            if(temp==1)
            {
                intarray.add(Integer.parseInt(strarray[i]));
                ar.add(Integer.parseInt(strarray[i]));
            }


        }


       ht="";
       String strdemo="";
       for(int i=0;i<intarray.size();i++)
       {

            if(ht=="")
            {

                ht=ar.get(i)+"";
        lastadded=i;
            }

        else
         {
             strdemo=(String)ht;
            if(strdemo.length()==ar.get(0).toString().length())
            {

   if(Integer.parseInt(strdemo.substring(0))==Integer.parseInt(ar.get(i).toString())-1)
             {
                 strdemo=strdemo+"-"+ar.get(i);
                 lastadded=Integer.parseInt(ar.get(i).toString());
                 ht=strdemo;
             }
             else
             {
                 strdemo=strdemo+","+ar.get(i);
                 lastadded=Integer.parseInt(ar.get(i).toString());
                 ht=strdemo;
             }
            }
            else if(strdemo.length()==3)
            {
                 strdemo=(String)ht;
                 if(Integer.parseInt(strdemo.substring(strdemo.length()-1,strdemo.length()))==Integer.parseInt(ar.get(i).toString())-1)
                 {
                     strdemo=strdemo.substring(0,strdemo.length()-2)+"-"+Integer.parseInt(ar.get(i).toString());
                     lastadded=Integer.parseInt(ar.get(i).toString());
                     ht=strdemo;
                 }
                 else
                 {
                     strdemo=strdemo+","+Integer.parseInt(ar.get(i).toString());
                     lastadded=Integer.parseInt(ar.get(i).toString());
                     ht=strdemo;
                 }
            }//Else IF
            else{
                strdemo=(String)ht;
                int de=1;


                int ddd=lastadded;
                 if(ddd==Integer.parseInt(ar.get(i).toString())-1)
                 {
                      int lastaddedlen=(lastadded+"").length();
                      String symbol=strdemo.substring(strdemo.length()-lastaddedlen-1,strdemo.length()-lastaddedlen);
                     if(symbol.equalsIgnoreCase("-"))
                       strdemo=strdemo.substring(0,strdemo.length()-lastaddedlen-1)+"-"+Integer.parseInt(ar.get(i).toString());
                     else
                     strdemo=strdemo+"-"+Integer.parseInt(ar.get(i).toString());
                     lastadded=Integer.parseInt(ar.get(i).toString());
                     ht=strdemo;
                 }
                 else
                 {
                     strdemo=strdemo+","+Integer.parseInt(ar.get(i).toString());
                     lastadded=Integer.parseInt(ar.get(i).toString());
                     ht=strdemo;
                 }
            }
    }
}

此处sortArray函数对数组进行降序排序并返回

protected static String[] sortArray(String ss[])
    {
        String temp;
        for(int i=0;i<ss.length;i++)
        {
            for(int j=0;j<ss.length;j++)
            {
             if(Integer.parseInt(ss[i])<Integer.parseInt(ss[j]))
             {
                temp=ss[i];
                ss[i]=ss[j];
                ss[j]=temp;
             }
            }
        }
        return ss;
    }

对于某些输入,我没有得到一致的结果,例如以下情况 2,3,6,7,8,10,12,14,15,16它提供了2-3,6-8,10,12,14-16,这是正确的) 而对于2,4,5,6,7,8,10,12,14,15,16,它会2-8,10,12,14-16 (which actually should have been 2,4-8,10,12,14-16 )

代码不一致的地方是我需要找到的......

2 个答案:

答案 0 :(得分:3)

这在Java中非常丑陋和冗长,但这是一个版本。注意,它在最后使用Spring中的StringUtils来处理将String集合转换为逗号分隔字符串的简单而又丑陋的过程。

关键是使用单独的类来模拟数值范围。让这个类知道如何将自己变成一个String。那么你就不会有如此多的逻辑来附加到StringBuilder。

另外,尝试从集合的角度思考。这总能让事情更加清晰。伪代码类似于:String变为List<Integer>变为List<Range>,最后变为String

public class Ranges {

    // A class that models a range of integers
    public static class Range {
        private int low;
        private int high;

        public Range(int low, int high) {
            this.low = low;
            this.high = high;
        }

        public int getHigh() {
            return high;
        }

        public void setHigh(int high) {
            this.high = high;
        }

        @Override
        public String toString() {
            return (low == high) ? String.valueOf(low) : String.format("%d-%d", low, high);
        }
    }

    public static void main(String[] args) {
        String input = "2,3,6,7,8,10,12,14,15,16";

        // Turn input string into a sorted list of integers
        List<Integer> inputNumbers = new ArrayList<Integer>();
        for (String num : input.split(",")) {
            inputNumbers.add(Integer.parseInt(num));
        }
        Collections.sort(inputNumbers);

        // Flatten list of integers into a (shorter) list of Ranges
        Range thisRange = null; // the current range being built
        List<Range> ranges = new ArrayList<Range>();
        for (Integer number : inputNumbers) {
            if (thisRange != null && number <= thisRange.getHigh() + 1) {
                // if we are already building a range (not null) && this new number is 
                // the old high end of the range + 1, change the high number.
                thisRange.setHigh(number);
            } else {
                // create a new range and add it to the list being built
                thisRange = new Range(number, number);
                ranges.add(thisRange);
            }
        }

        // Join List<String> into a single String
        String result = StringUtils.collectionToCommaDelimitedString(ranges);
        System.out.println("result = " + result);
    }
}

答案 1 :(得分:0)

这是我的实施。希望这有帮助。

您必须传递这些值 例如int[] a = {2,3,4,5,6,7,8,10,12, 14,15,16,18,19,21,22,26}; 以下方法。

public List<String> listIntRange(int[] values)
{
    List<String> intRangeList = new ArrayList<String>();

    int first = 0;
    int current = 0;
    int prev = 0;
    int count = 0;

    if (values == null || values.length < 1)
        return intRangeList;

    first = prev = values[0];
    int index = 1;
    boolean range = false;
    for(index = 1; index < values.length; index++)
    {
        current = values[index];
        if(current - prev == 1)
        {
            range = true;   
            prev = current;
            continue;
        }

        if(range == true)
        {
            intRangeList.add(first + "-" + prev);
        }
        else
        {
            intRangeList.add("" + first);
        }

        first = current;
        prev = current;
        range = false;

    }

    if(range == true)
    {
        intRangeList.add(first + "-" + current);
    }
    else
    {
        intRangeList.add("" + current);
    }

    return intRangeList;
}

当打印出intRangeList:

中的值时,输出如下所示
2-8,10,12,14-16,18-19,21-22,26,

请忽略最后一个逗号','。