How can I sort a string "13,5,8,4,2,1,9"
in ascendin开发者_Python百科g order, to get 1,2,4,5,8,9,13
?
- Split the string by commas
- Parse each substring into an integer
- Sort the resulting collection
- If you need the result to be a string (it's not clear), convert each integer back into a string and join them together with commas.
If any of those steps causes you difficulties, please be more specific.
- Split it into an array of items with
String.split()
. - Convert to an array of numbers with
Integer.valueOf()
. - Sort the array.
- Concatenate it all back into a
StringBuilder
.
As one liner, using Google Collections (updated with Kevin's suggestion)
Joiner.on(",").join(Ordering.natural().onResultOf(new Function<String, Integer>() {
@Override
public Integer apply(String from) {
return Integer.valueOf(from);
}
}).sortedCopy(Arrays.asList("4,2,7,9,1".split(","))));
- Split using
String.split()
- Transform to
Integer
using aFunction
(anyone know if there's a constant for this one somewhere?) - Sort using a
TreeSet
and natural ordering - Join the parts and transform back to a
String
usingJoiner
(old version)
Joiner.on(',').join(
Sets.newTreeSet(
Iterables.transform(
Arrays.asList("13,5,8,4,2,1,9".split(",")),
new Function<String, Integer>() {
@Override
public Integer apply(String from) {
return Integer.parseInt(from);
}}))));
String s = "13,5,8,4,2,1,9";
String[] arr = s.split(",");
Arrays.sort(arr, new Comparator<String>() {
@Override public int compare(String s1, String s2) {
return Integer.parseInt(s1) - Integer.parseInt(s2);
}
});
s = Arrays.toString(arr).replaceAll("[\\[ \\]]", "");
This solution uses:
java.util.Comparator
java.util.Arrays
sort
andtoString
String
split
andreplaceAll
- regular expression
I would tokenize the string using StringTokenizer,
parse the values (using Integer.parseInt),
then sort the results using Arrays.sort.
Lastly, re-create the string.
String str = "13,5,8,4,2,1,9";
StringTokenizer tokens = new StringTokenizer(", ");
ArrayList<Integer> ints = new ArrayList<Integer>();
for(String token: tokens)
ints.add(Integer.parseInt(token));
Collection.sort(ints);
String sortedStr = "";
for(int i = 0; i + 1 < ints.size(); ++i)
sortedStr += ints.get(i) + ", ";
if (ints.size() > 0)
sortedStr += ints.lastElement();
Might have some misspellings, but I think not. Also, add the appropriate imports yourself =)
So you have a string containing a comma-delimited set of integers that you need to sort and then output to a string? Try split
-ting the string, parse
-ing the integers, sort
-ing the resulting array, and then join
-ing the results together
Java 8+
If you are using Java 8 you can use streams to sort like so :
String str = "13,5,8,4,2,1,9";
String sortedString =
Arrays.stream(str.split(",")) //split with ','
.map(Integer::valueOf) //convert your strings to ints
.sorted() //sort
.map(String::valueOf) //convert them back to string
.collect(Collectors.joining(","));//1,2,4,5,8,9,13
If you want an sorted array you can also use :
Integer[] sortedInts =
Arrays.stream(str.split(",")) //split with ','
.map(Integer::valueOf) //convert your strings to ints
.sorted() //sort
.toArray(Integer[]::new);//[1, 2, 4, 5, 8, 9, 13]
The idea is the same as Jon Skeet explanation.
An alternative using java.util.Scanner
public class SortString {
public static void main( String [] args ) {
// Read integers using Scanner...
Scanner scanner = new Scanner( "13,5,8,4,2,1,9" ).useDelimiter(",");
// Put them in a Integer list
List<Integer> list = new ArrayList<Integer>();
while( scanner.hasNextInt() ){
list.add( scanner.nextInt() );
}
// And sort it
Collections.sort( list );
System.out.println( list );
}
}
ok you can try this one it work in all case.
package com.java;
import java.util.*;
public class cd
{
public static void main(String s[])
{
Collections col;
List l = sort(s);
System.out.println("\nStrings sorted List ...");
for(int i = 0; i < s.length; i++)
{
System.out.println((String)l.get(i));
}
int ints[] = {
719, 2, -22, 401, 6
};
Integer in[] = new Integer[ints.length];
for(int i = 0; i < in.length; i++)
{
in[i] = new Integer(ints[i]);
}
l = sort(in);
System.out.println("\nIntegers sorted List ...");
for(int i = 0; i < in.length; i++)
{
System.out.println((Integer)l.get(i));
}
}
public static List sort(Object o[])
{
ArrayList al = new ArrayList();
for(int i = 0; i < o.length; i++)
al.add(i, o[i]);
List list = Collections.synchronizedList(al);
Collections.sort(list);
return list;
}
}
This is one way to sorting.
package com.java;
import java.util.ArrayList;
import java.util.Collections;
public class b{
public static void main(String[] args) {
//create an ArrayList object
ArrayList arrayList = new ArrayList();
//Add elements to Arraylist
arrayList.add("9");
arrayList.add("3");
arrayList.add("5");
arrayList.add("2");
arrayList.add("4");
Collections.sort(arrayList);
//display elements of ArrayList
System.out.println("ArrayList elements after sorting in ascending order : ");
for(int i=0; i<arrayList.size(); i++)
System.out.println(arrayList.get(i));
}
}
class SplitStr
{
public static void main(String args[])
{
try
{
String str=args[0]+","+args[1]; //marge two string in one
String sArr[]=str.split(",");
int slen=sArr.length;
int iArr[]=new int[slen];
int temp;
for(int i=0;i<slen;i++)
{
iArr[i]=Integer.parseInt(sArr[i]); //convert String into integer array
}
for(int i=0;i<slen;i++)
{
for(int j=i+1;j<slen;j++)
{
if(iArr[i]>=iArr[j])
{
temp=iArr[i];
iArr[i]=iArr[j];
iArr[j]=temp;
}
}
}
for(int i=0;i<slen;i++)
{
System.out.println(" "+iArr[i]);
}
}
catch(Exception e)
{
System.out.println("input error "+e);
}
}
}
Bash is SO powerful :-)
numbers="1, 2, 9, 4, 7, 5" ; for number in $(echo "$numbers") ; do echo "$number" | tr -d ", "; done | sort | tr "\n" "," ; echo ""
精彩评论