Skip to main content

APIzation: Replication Package

[Q#2529045][A#2529114] How do I sort strings that contain numbers in Java

https://stackoverflow.com/q/2529045

I want to sort a String that has nr. How do I do that? Lets say my integers are in main I do class2.Sort(); Thanks in Advance.

Answer

https://stackoverflow.com/a/2529114

APIzation

public static void main(String[] args)
  {
    String string = "3 42 \n   11   \t  7  dsfss  365          \r   1";
    String[] numbers = string.split("\\D+");
    Arrays.sort(numbers, new Comparator<String>()
    {
      public int compare(String s1, String s2)
      {
        return Integer.valueOf(s1).compareTo(Integer.valueOf(s2));
      }
    });
    System.out.println(Arrays.toString(numbers));
  }
package com.stackoverflow.api;

import java.util.Arrays;
import java.util.Comparator;

public class Human2529114 {

  public static String sortStringContainingNumbers(String string) {
    String[] numbers = string.split("\\D+");
    Arrays.sort(
      numbers,
      new Comparator<String>() {
        public int compare(String s1, String s2) {
          return Integer.valueOf(s1).compareTo(Integer.valueOf(s2));
        }
      }
    );
    return Arrays.toString(numbers);
  }
}

package com.stackoverflow.api;

import java.util.Arrays;
import java.util.Comparator;

/**
 * How do I sort strings that contain numbers in Java
 *
 * @author APIzator
 * @see <a href="https://stackoverflow.com/a/2529114">https://stackoverflow.com/a/2529114</a>
 */
public class APIzator2529114 {

  public static String sortString(String string) {
    String[] numbers = string.split("\\D+");
    Arrays.sort(
      numbers,
      new Comparator<String>() {
        public int compare(String s1, String s2) {
          return Integer.valueOf(s1).compareTo(Integer.valueOf(s2));
        }
      }
    );
    return Arrays.toString(numbers);
  }
}