Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7848049
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T18:04:21+00:00 2026-06-02T18:04:21+00:00

I want to convert a string input like 2,3,6,7,8,10,12,14,15,16 to 2-3,6-8,10,12,14-16 using java I

  • 0

I want to convert a string input like 2,3,6,7,8,10,12,14,15,16 to 2-3,6-8,10,12,14-16 using java

I tried using the below code

        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;
                 }
            }
    }
}

Here sortArray function sorts the array descending and returns

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;
    }

I am not getting consistant results for some inputs for example for the below case
2,3,6,7,8,10,12,14,15,16 it gives 2-3,6-8,10,12,14-16 (which is correct)
while for 2,4,5,6,7,8,10,12,14,15,16 it gives 2-8,10,12,14-16 (which actually should have been 2,4-8,10,12,14-16)

Where does the code go inconsistent is what I need to find out..

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-02T18:04:22+00:00Added an answer on June 2, 2026 at 6:04 pm

    This is pretty ugly and verbose in Java, but here is a version. Note, it uses StringUtils from Spring at the very end for the trivial but also ugly process of converting a String collection to a comma delimited string.

    The key is to use a separate class to model the numeric ranges. Let this class know how to turn itself into a String. Then you won’t have so much logic around appending to a StringBuilder.

    Also, try to think in terms of collections. This always makes things clearer. The pseudo-code is something like: String becomes List<Integer> becomes List<Range> and finally becomes 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);
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to convert a string like 2012-03-08T00:00:00+01:00 into Date.. I tried to use
I want to convert an string to an enum type using TValue, I googled
I want to convert below string to an array in javascript. {a:12, b:c, foo:bar}
I want to convert user input that comes as Map<String, String[]> to objects in
I am getting the value of input using javascript using below code. var name=document.getElementById(firstName).value;
I want to convert String to Date in different formats. For example, I am
I want to convert a string into a double and after doing some math
I want to convert a string into a series of Keycodes, so that I
i want to convert this string into DateTime. Tue Aug 19 15:05:05 +0000 2008
I want to convert a string representations of few dozen enum types to enum

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.