Substituting Number Ranges with the Numbers

paulca
paulca used Ask the Experts™
on
If I have a string in the form of 3-6, how do I convert it so that it reads 3,4,5,6?  Thanks.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
public class Test
{
     public static void main( String args[] )
     {
          String s1 = "3456", s2 = "";

          for( int i = 0; i < 4; i++ )
          {
                s2 += s1.charAt(i);
                if( i != 3 )
                      s2 += ",";
          }

          System.out.println( s1 + "\n" + s2 );
     }
}

Commented:
public class Test
{
  public static void main(String args[])
  {
    String str = args[0];

    int dash = str.indexOf('-');

    int from = Integer.parseInt(str.substring(0, dash));
    int to = Integer.parseInt(str.substring(dash+1));

    StringBuffer sb = new StringBuffer();
    for (int i = from; i <= to; i++)
    {
       sb.append(i).append(',');
    }

    sb.deleteCharAt(sb.length()-1);

    String result = sb.toString();

    System.out.println( str + ": " + result );
  }
}

Try

java Test 3-6

will print out  3,4,5,6
Use String Tokenizer to seperate number ranges.

java.util.StringTokenizer x = new java.util.StringTokenizer("3-4-5-6","-");
int size =     x.countTokens();
String concatenatedString = "";
for(int i=0;i<size;i++)
{
     concatenatedString+=x.nextElement();
     if(i != ( size -1 ))
     {
     concatenatedString+=",";
     }
}
System.out.println(concatenatedString);
This prints 3,4,5,6
Ovi

Commented:
See kotan solution

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial