4

我想使用 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)

代码哪里不一致是我需要找出的..

4

2 回答 2

3

这在 Java 中非常丑陋和冗长,但这里有一个版本。请注意,它在最后使用来自 Spring 的 StringUtils 来完成将 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);
    }
}
于 2012-04-26T06:35:52.757 回答
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,

请忽略最后一个逗号“,”。

于 2012-04-26T07:44:07.877 回答