-9

I am having an array

int arr[]={1,$,2,3,$,$,4,5}

and want the output as

arr[]={1,2,3,4,5,$,$,$}

Can you please help me

My code is

public class ArrayTest
{
    static void splitString(String str)
    {
        StringBuffer alpha = new StringBuffer(), 
        num = new StringBuffer(), special = new StringBuffer();

        for (int i=0; i<str.length(); i++)
        {
            if (Character.isDigit(str.charAt(i)))
                num.append(str.charAt(i));

            else
                special.append(str.charAt(i));
        }


        System.out.print(num);
        System.out.print(special);
    }

    public static void main(String args[])
    {
        String str = "1,2,$,$,3,4";
        splitString(str);
    }
}

I am getting the O/P as 1234,,$,$,, instead of 1,2,3,4,$,$

Vineet
  • 1
  • 1

2 Answers2

0

Sorting is not single activity. Sorting is actually ordering, and comparing.

You can use Java built-in sorting but your own comparator (piece of code that knows how to compare).

Your comparator, need to make sure that special sign is just bigger then any other value (and is equal to any other special sign). If neither compared value is special sign, do ordinary comparison.

Here is link to other question that explains how to do that: How to use Comparator in Java to sort

przemo_li
  • 3,932
  • 4
  • 35
  • 60
0

From your output I can see that your function includes the commas in the sorting as well. You must remove the commas before sorting the String:

 str = str.replaceAll(",", "");

This line of code will replace all commas with nothing, or in other words remove them. Now you can execupe your sorting algorithm and add the commas at the end:

String merge = num.toString() + special.toString();
String result = "";
for (int i = 0; i < merge.length(); ++i) {
    result += merge.charAt(i) + ",";
}

This will put an additional comma at the end which you can remove very easily:

result = result.substring(0, result.length() - 1);

Now result holds the wanted result.

Loading BG
  • 131
  • 2
  • 9