Sorting a String

Hi,
I was wondering how would I sort the following String using String class methods and StringTokenizer.
For example.
Input: String a = 12hello^25hello^10hello;
Sort it chronologically
Output String a = 10hello^12hello^25hello;
Thanks in advance.

In Java 5.0, something like the following?
import java.util.Arrays;
import java.util.Comparator;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Test {
    public static void main(String[] args) {
        String a = "12hello^25hello^10hello^100hello";
        String[] tokens = a.split("\\^");
        Arrays.sort(tokens, new Comparator<String>() {
            String regexp = "(\\d+)";
            Pattern p = Pattern.compile(regexp);
            public int compare(String s1, String s2) {
                Matcher m1 = p.matcher(s1);
                Matcher m2 = p.matcher(s2);
                if (!m1.find() || !m2.find()) {
                    return s1.compareTo(s2);
                int i1 = Integer.parseInt(m1.group(1));
                int i2 = Integer.parseInt(m2.group(1));
                if (i1 < i2) {
                    return -1;
                } else if (i1 > i2) {
                    return 1;
                } else {
                    return s1.compareTo(s2);
        StringBuilder sb = new StringBuilder();
        for (String b : tokens) {
            sb.append("^").append(b);
        String result = sb.toString().substring(1);
        System.out.println(result);
}Beware, I haven't checked this for bugs. You'd probably want to check the logic of the comparator ;-)
Cheers, Neil

Similar Messages

  • Sort a string :: Please help.

    Hello Everyone,
    I am having this very simple problem of sorting a String. please help.
         static String sortString(String str){
              List list = Arrays.asList(str);                    
              Collections.sort(list);
              for(int i=0, n=list.size();i<n;i++){
                   System.out.println(","+ list.get(i));
    The function is supposed to take a String and sort it & print it out. This should be simple. Where am I making mistakes? Please help!!

    Hello Everyone,
    I am having this very simple problem of sorting a String. please help.
         static String sortString(String str){
              List list = Arrays.asList(str);                    
              Collections.sort(list);
              for(int i=0, n=list.size();i<n;i++){
                   System.out.println(","+ list.get(i));
                   return str;
    The function is supposed to take a String and sort it & print it out. This should be simple. Where am I making mistakes? Please help!!

  • Problem in sorting numeric string

    hii
    i have created one method using comparator and passed a list with list of strings as argument to sort method of Collections class.The string ,which is combined a string and numeric value for example A1,A2,A11,A3 .....So i wanted the result as A1,A2,A3..A11,A12... and so on as final output.but when i print the output ,they are sorted as A1,A11,A12....A2,A3....so i learned from javadoc why those are sorted as like since comparator is using charAt() method while making override compare() method.but i am not expected this sorting for my application. i need sorting output as A1,A2,A3...A11,A12.....How to compare a string with another string both have combination of string and number using java?
    if any one know the logic reply me.
    i have pasted my code,if any changes have to be made only in this code,correct the code.
    package sample.sorting;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    public class SortString {
         public static List<String> sort(List<String> data) {
              Collections.sort(data,new Comparator<String>(){
                   public int compare(String s1,String s2) {
                        return s1.compareTo(s2)     ;
              return data;
         public static void main(String[] args) {
              List<String> sortList     = new ArrayList<String>();
              sortList.add("A1");
              sortList.add("A3");
              sortList.add("A2");
              sortList.add("A9");
              sortList.add("A11");
              sortList.add("A6");
              List<String> sort = sort(sortList);
              for(String str : sort) {
                   System.out.println("STR :: "+str); // O/P : A1,A11,A2,A3,A6... but expected O/P : A1,A2,A3..A11.
    }thanks in advance.
    with regards
    Oasisderts
    Edited by: oasisdesert on Dec 29, 2009 4:15 AM

    In the compare method of the comparator, check if two Strings have equal length, if so compare them as normal, otherwise treat them as a separate case.
    e.g. uncompiled return s1.length == s2.length ? s1.compareTo(s2) : if(s1.length < s2.length) -1 else 1;Mel

  • How can I sort a string

    Hi,
    I want to sort a string (daycode), I use the daycode to sort my data. Now i want to sort the daycodes, but i do not know how.
    Example: the daycode is a10r, so a is the first shift in week (b the second and so on), 10 is the week in year, r is the year.
    Now i have a array with daycode-strings and want to sort it to year, week, shift (normaly it is sorted to the first letter).
    Someone with a good idea???
    Thanks a lot
    Marco

    Try this vi and see if it is something you might be looking for and if not maybe you could explain a little more about what you want to do.
    Joe.
    "NOTHING IS EVER EASY"
    Attachments:
    sort.vi ‏15 KB

  • Sort / compare Strings   SOS ... ___ ...

    Hi, sorry I'm novice in Java, and I'm trying to make kind of bubble sort on String MyArray[]. God ! I just found out that I can't compare Strings i.e. Objects like:
    if ( MyArray[i] > MyArray)...
    Can anybody recommend me a not too complicated solution, preferebly without imports..
    Thanks
    Mario

    Hi.
    String.compareTo(String anotherString) is what you need. Have a look at http://java.sun.com/j2se/1.4/docs/api/java/lang/String.html#compareTo(java.lang.String)
    Regards,
    Lance
    Lance Walton - [email protected]
    Team In A Box - Software without Tragedy
    http://www.teaminabox.co.uk

  • Having probs with radix Sort for strings

    I am creating a method that does radix sort for string values. I think I need to know the maximum value for strings to do this, and I have no Idea what that would be

    As in the maximum size of a string?
    Do you mean characters or actual byte size?

  • Newbie trying to sort 2D string array

    Dear all,
    After read some book chapters, web sites including this, I still don't get the point.
    If I have a file like,
    1 aaa 213 0.9
    3 cbb 514 0.1
    2 abc 219 1.3
    9 bbc 417 10.4
    8 dee 887 2.1
    9 bba 111 7.1
    and I load into memory as a String[][]
    here comes the problem, I sort by column 1 (aaa,...,bba) using an adaptation of the Quicksort algorithm for 2D arrays
    * Sort for a 2D String array
    * @param a an String 2D array
    * @param column column to be sort
    public static void sort(String[][] a, int column) throws Exception {
    QuickSort(a, 0, a.length - 1, column);
    /** Sort elements using QuickSort algorithm
    static void QuickSort(String[][] a, int lo0, int hi0, int column) throws Exception {
    int lo = lo0;
    int hi = hi0;
    int mid;
    String mitad;
    if ( hi0 > lo0) {
    /* Arbitrarily establishing partition element as the midpoint of
    * the array.
    mid = ( lo0 + hi0 ) / 2 ;
    mitad = a[mid][column];
    // loop through the array until indices cross
    while( lo <= hi ) {
    /* find the first element that is greater than or equal to
    * the partition element starting from the left Index.
    while( ( lo < hi0 ) && ( a[lo][column].compareTo(mitad)<0))
    ++lo;
    /* find an element that is smaller than or equal to
    * the partition element starting from the right Index.
    while( ( hi > lo0 ) && ( a[hi][column].compareTo(mitad)>0))
    --hi;
    // if the indexes have not crossed, swap
    if( lo <= hi )
    swap(a, lo, hi);
    ++lo;
    --hi;
    /* If the right index has not reached the left side of array
    * must now sort the left partition.
    if( lo0 < hi )
    QuickSort( a, lo0, hi, column );
    /* If the left index has not reached the right side of array
    * must now sort the right partition.
    if( lo < hi0 )
    QuickSort( a, lo, hi0, column );
    * swap 2D String column
    private static void swap(String[][] array, int k1, int k2){
    String[] temp = array[k1];
    array[k1] = array[k2];
    array[k2] = temp;
    ----- end of the code --------
    if I call this from the main module like this
    import MyUtil.*;
    public class kaka
    public static void main(String[] args) throws Exception
    String[][]a = MyUtil.fileToArray("array.txt");
    MyMatrix.printf(a);
    System.out.println("");
    MyMatrix.sort(a,1);
    MyMatrix.printf(a);
    System.out.println("");
    MyMatrix.sort(a,3);
    MyMatrix.printf(a);
    for the first sorting I get
    1 aaa 213 0.9
    2 abc 219 1.3
    9 bba 111 7.1
    9 bbc 417 10.4
    3 cbb 514 0.1
    8 dee 887 2.1
    (lexicographic)
    but for the second one (column 3) I get
    3 cbb 514 0.1
    1 aaa 213 0.9
    2 abc 219 1.3
    9 bbc 417 10.4
    8 dee 887 2.1
    9 bba 111 7.1
    this is not the order I want to apply to this sorting, I would like to create my own one. but or I can't or I don't know how to use a comparator on this case.
    I don't know if I am rediscovering the wheel with my (Sort String[][], but I think that has be an easy way to sort arrays of arrays better than this one.
    I've been trying to understand the Question of the week 106 (http://developer.java.sun.com/developer/qow/archive/106/) that sounds similar, and perfect for my case. But I don't know how to pass my arrays values to the class Fred().
    Any help will be deeply appreciated
    Thanks for your help and your attention
    Pedro

    public class StringArrayComparator implements Comparator {
      int sortColumn = 0;
      public int setSortColumn(c) { sortColumn = c; }
      public int compareTo(Object o1, Object o2) {
        if (o1 == null && o2 == null)
          return 0;
        if (o1 == null)
          return -1;
        if (o2 == null)
          return 1;
        String[] s1 = (String[])o1;
        String[] s2 = (String[])o2;
        // I assume the elements at position sortColumn is
        // not null nor out of bounds.
        return s1[sortColumn].compareTo(s2[sortColumn]);
    // Then you can use this to sort the 2D array:
    Comparator comparator = new StringArrayComparator();
    comparator.setSortColumn(0); // sort by first column
    String[][] array = ...
    Arrays.sort(array, comparator);I haven't tested the code, so there might be some compiler errors, or an error in the logic.

  • Sorting a String Array in alpha order (Using ArrayList)

    Hello all!
    I am pretty new to Java and am trying to do a, seemingly, simple task; but cannot get the syntax right. I am trying to sort an ArrayList in aplha order based off of the variable String Product. Any help would be awesome!
    First Class:
    //This program stores all of the variables for use in Inventory.java
    public class Vars {
         // defining all variables
         private String product;
         private String prodCode;
         private double price;
         private double invCount;
         // Begin listing getters for class
         public Vars(String product) {
              this.product = product;
         public String getProdCode() {
              return prodCode;
         public String getProduct() {
              return product;
         public double getPrice() {
              return price;
         public double getInvCount() {
              return invCount;
         // Declaring the total variable
         public double total() {
              return invCount * price;
         // Begin listing setters for variables
         public void setProduct(String product) {
              this.product = product;
         public void setProdCode(String prodCode) {
              this.prodCode = prodCode;
         public void setInvCount(double invCount) {
              this.invCount = invCount;
         public void setPrice(double price) {
              this.price = price;
    Second Class:
    //This program will use the variables stored in Vars.java
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
    public class Inventory {
         public static void main(String args[]) {
              Scanner input = new Scanner(System.in);
              //defining and declaring local variables
              String exit;
              int counter;
              double gtotal;
              exit = "exit";
              counter = 0;
              gtotal = 0;
              //beginning message and beginning of the loop
              System.out.print("Welcome to the Inventory Contol System\nPlease enter the Product name: ");
              System.out.println();
              System.out.println("When finished entering in the data, please enter EXIT in place of Product name.");
              String name = input.next();
              List<Vars> var = new ArrayList<Vars>(); //creating arraylist object
              //loop while exit is not entered, exit loop once exit is typed into product variable
              while (name.compareToIgnoreCase(exit) != 0) {
                   Vars vars = new Vars(name); //calling Vars methods
                   counter = counter ++;
                   System.out.println("Please enter the Product Code: ");
                   vars.setProdCode(input.next());
                   System.out.println("Inventory Count: ");
                   vars.setInvCount(input.nextDouble());
                   //Making sure that the value entered is a positive one
                   if(vars.getInvCount() < 0){
                        System.out.println("Please enter a positive number: ");
                        vars.setInvCount(input.nextDouble());
                   System.out.println("Price per product:");
                   vars.setPrice(input.nextDouble());
                   //Making sure that the value entered is a positive one
                   if(vars.getPrice() < 0) {
                        System.out.println("Please enter a positive number: ");
                        vars.setPrice(input.nextDouble());
                   System.out.println("Please enter the next Product name, or enter EXIT: ");
                   name = input.next();
                   gtotal += vars.total(); //calculation for Grand Total of all products entered
                   var.add(vars);
                   static void slectionSort(int[] product) {
                   for (int lastPlace = product.length-1; lastPlace > 0; lastPlace--) {
                   int maxLoc = 0;
                   for (int j = 1; j <= lastPlace; j++) {
                   if (product[j] > product[maxLoc]) {
                   maxLoc = j;
                   int temp = product[maxLoc];
                   product[maxLoc] = product[lastPlace];
                   product[lastPlace] = temp;
              //Sorting loop function will go here, before the information is displayed
              //Exit message and array list headers
              System.out.print("Thank you for using the Inventory program.\nHave a wonderful day.\n");
              System.out.printf("Code\tProduct\tCount\tPrice\tTotal\n");
              System.out.println();
              //For loop to display all entries via an ArrayList
              for (Vars vars : var) {
                   System.out.printf("%5s\t%5s\t%.01f\t$%.02f\t$%.02f\n\n", vars.getProdCode(),
                             vars.getProduct(), vars.getInvCount(), vars.getPrice(),vars.total());
              //Displays the amount of entries made and Grand Total of all products entered
              System.out.println();
              System.out.printf("The number of products entered is %d\n", var.size());
              System.out.printf("The Grand Total cost for the products entered is $ %s\n", gtotal);
              System.out.println();
    }

    go through below links, you can easily understand how to sort lists.
    http://www.onjava.com/lpt/a/3286
    http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html
    http://www.javaworld.com/javaworld/jw-12-2002/jw-1227-sort.html

  • Sort Alphanumeric string in OBIEE answers

    Hi...
    I have a time slot column in my table. I holds data as follows,
    10AM-12PM
    9AM-11AM
    11AM-1PM
    How to sort the report with these column. If i sort it, it was showing data as follows.
    10AM-12PM
    11AM-1PM
    9AM-11AM
    Can u please help to reslove the issue

    If you are specifically trying to use a string function to resolve your issue, then you can try below.
    Pull another slot column in your Answers request and use evaluate function, to derive a timestamp (using oracle to_date funtion) column. Then you can sort this column and hide it in your report.
    Something like below can be used derive timestamp from say '10AM-11AM':
    select to_date(substr('10AM-11AM',1,instr('10AM-11AM','-')-1),'HHAM') from dual --Output 2011-09-01 10:00:00
    Similarly,
    select to_date(substr('10PM-11PM',1,instr('10PM-11PM','-')-1),'HHAM') from dual --Output 2011-09-01 22:00:00
    See if it suits your requirement.
    Thanks

  • WHERE Clause sorting via String

    Hi, I am joining 2 tables together while using DISTINCT in the Select statement but i need to sort all the rows that only match by Date '1996'. Problem is the conversion of the Date/Time value is not a String i need to return only the rows where companies
    only placed orders in 1996.
    I have also tried WHERE o.OrderDate LIKE '[1996]%'
    Select DISTINCT CompanyName
    From Customers c
    JOIN Orders o ON o.OrderDate = c.CompanyName
    WHERE o.OrderDate = '1996'
    Order By CompanyName ASC;

    I have to use DISTINCT & JOIN both tables it is apart of my assignment i have no choice in the matter.
    I don't care what your professor tells you. I care that you learn SQL properly. And, hey, chances are good that I know T-SQL better than your professor.
    DISTINCT is a highly abused keyword. To the extent that I would say that anytime you feel compelled to put in DISTINCT, you should start thinking if you might have gone wrong somewhere in the query. In a properly written join, there is rarely a need for
    DISTINCT. If it happens, it may be one of the following:
    1) Incomplete join-conditions. You joined two tables on a single column, when there is a two-column key linking them. That is, an error in the query.
    2) The table that introduces duplicates in the query is not included in the SELECT list, because the table only appears in the query to check existence. This is your case, and you should use EXISTS instead (no matter what your professor asks you for).
    3) You only include a subset of the columns from the tables in the query, and in those columns alone there is a duplicate. This may be a legit case, because you may only be looking for the distinct values. But you should review the requirements first.
    I don't list these points because I am bored on a Saturday night. I list these points, because I see these errors over and over again by inexperienced programmers on the forums. And for that matter not-so-inexperienced programmers who once learnt bad
    habits, and still are sticking to them.
    So, OK, show your professor the query with JOIN and DISTINCT. But also show him the query with EXISTS. Also make sure that you understand how that query works. Your professor may or may not be impressed, but that does not matter. You learn for life, and
    not to impress your professor.
    And, oh, one more thing. The condition on OrderDate should really be:
     AND  O.OrderDate >= '19960101'
     AND  O.OrderDate < '19970101'
    This is guaranteed to do an IndexSeek on OrderDate if the optimizer finds that this is the best solution. (Which it will not in this case, because you are looking at one third of all orders.) On the other hand, the condition that Ronen is trying to lure
    you to use:
       WHERE datepart(year,o.OrderDate) = 1996
    may or may not seek the index, depending on how the optimizer is implemented this year.
    I realise that the talk about indexes and optimizer may go above your head at this point, but again, I am eager that you learn best practices early, and that you don't learn things you will need to unlearn later. You can remember this lesson in this
    way: never entangle a column into an expression, if you can resolve the condition with simple comparison operations.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • TreeSet vs Collection.Sort / Array.sort for Strings

    Gurus
    I am pondering weather to use TreeSet vs the Collections.sort / Array.sort for sorting Strings.
    Basically I have a list of Strings, i need to perform the following operations on these Strings
    1) Able to list Strings starting with a Prefix
    2) Able to list Strings Lexically greater than a String
    Any help would be greatly appreciated!
    Thanks a bunch

    SpaceShuttle wrote:
    Gurus
    I am pondering weather to use TreeSet vs the Collections.sort / Array.sort for sorting Strings.
    Basically I have a list of Strings, i need to perform the following operations on these Strings
    1) Able to list Strings starting with a Prefix
    2) Able to list Strings Lexically greater than a String
    Any help would be greatly appreciated!
    Thanks a bunchBig-O wise, there's no difference between sorting a list of N elements or inserting them one by one in a tree-set. Both take O(n*log(n)). But both collections are not well suited for looking up string that start with a certain substring. In that case you had better use a Patricia tree (or Radix tree).
    Good luck.

  • Unable to sort the strings

    Hi ,
    I have a table which stores some strings like :
    Create Table Sample2 (C1 Varchar2(20));
    Insert Into Sample2 Values('^!12');
    Insert Into Sample2 Values('9.2345353');
    Insert Into Sample2 Values('%!5');
    I am trying to do a ascending sort on the c1 column in sample2 table, but i see wierd results : the
    output of the query is like :
    SQL> select * from sample2 order by c1 asc
    Output:
    %!5
    9.2345353
    ^!12
    But if you see the above output the value '9.2345353' should appear at the end (bcoz it has the highest ascii value), but i see in the second row.can you please let me know, why it is happening ...
    Thanks

    CharlesRoos wrote:
    WITH t AS
    (SELECT '%!5' C1
    FROM Dual
    UNION ALL
    SELECT '9.2345353' C1
    FROM Dual
    UNION ALL
    SELECT '^!12' C1 FROM Dual)
    SELECT * FROM t ORDER BY Lower(C1)
    ^!12
    %!5
    9.2345353
    */;Ordering is like string functions and other such operations, depending, of database character set.And how is that supposed to work?
    SQL> ed
    Wrote file afiedt.buf
      1  with t as (
      2  select '%!5' as c1 from dual union all
      3  select '9.2345353' as c1 from dual union all
      4  select '^!12' as c1 from dual
      5  )
      6  --
      7  select c1
      8  from t
      9* order by lower(c1)
    SQL> /
    C1
    %!5
    9.2345353
    ^!12
    SQL>... cos it doesn't for me. The LOWER of a non alpha character is the same as the character itself.

  • Sorting 2D string array

    Hi I am new to labview. I want to sort my 2D string array by col 1. But I dont know how to sort it perfectly. My sorted array will be something like this.
    Col 1
    A1
    A2
    A3
    A4
    A5
    A6
    A7
    A8
    A9
    A10
    A11

    duplicate, see: http://forums.ni.com/ni/board/message?board.id=170&thread.id=317581&jump=true
    LabVIEW Champion . Do more with less code and in less time .

  • Sort an String Array

    Im having trouble sorting an Array. Before i add my new post to a[0] I would like to push all values one step. So value of a[0] will be stored in a[1] and value of [1] will be stored in [2] before a[0] = new value.
    I haven found a way yet, anyone else?
    Sebastian Green

    Hmm, I worked my own way of handle it. Like this:
    for (int i=4; i >= 0 ; i--) {
                   if (i==0){
                        a[i] = getNewData();
                   } else {
                        a[i] = a[i-1];
                 }Which one is best? I could set the "int=4" dynamiclly . But why should I use Vector? I thought that it would be better with a String[]. Then I have set the amount of memory to use for my Array? Or is is better to store it in an Vector and call New Vector () every round so the size dosent get large then it has to?

  • Jtable sorting question - string works, but numbers don't

    Hi,
    I have a Jtable which is populated from an Object two-dimensional array (myData). The object itself already containes string types and int types as appropriate (after a cumbersome type conversion).
    I can sort by the string column, but the number column does not get sorted correctly..i.e it shows 1, 11, 2, 3, 33, 50..etc..
    below is the code I am using:
    JScrollPane jScrollPane1 = new javax.swing.JScrollPane();
    JTable jTable1 = new JTable(myData,columNames);
    jTable1.setAutoCreateRowSorter(true);
    add(new JScrollPane(jTable1));
    jScrollPane1.setViewportView(jTable1);
    Can anyone help?
    thanks

    so, could you show me how to do what he suggests, override the getColumnClass thingy
    I can't figure it out.
    package tableclass;
    import java.awt.BorderLayout;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    public class EditorTest extends JFrame
        JTable table = new JTable(10, 5);
        public EditorTest()
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            JScrollPane scrollPane = new JScrollPane( table );
            getContentPane().add( scrollPane, BorderLayout.SOUTH);
        @Override;
        public class getColumnClass(int columnIndex){
            //idk wtf i'm doing.
        public static void main(String[] args)
            EditorTest frame = new EditorTest();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
    }

Maybe you are looking for

  • ICal: an unexpected network error (code 60)

    Hi Can somebody explain how to solve this? I have this for over a week now, and all the previous advice I followed, but did not work. Your help is much appreciated. Kr. Eva

  • AWM on 10.1.0.4 database, but looking at data in 9.0.4 database (DBlink)

    Hi, I have 2 databases; one running OAS and INFRA database (10.1.0.4) and one older datawarehouse (9.0.4). I have installed Analytical Workspace Manager and mounted the 10.1.0.4 database with the OLAP option. I would like to map the workspace dimensi

  • Need Coding!!!!!!!!!!!

    Dear All, I need to create Vendors Ageing Report in SAP version 4.7. As there is already a standard program name "RFKOPR00" available and need to be customized based on my requirement. I want output to be displayed in ALV grid format having all these

  • Setting ringer to silent for a single number

    I don't know how to do this. But i have a few numbers that i want to set so that when they call they don't have a ringer. I can't seem to find a way to set a single number to not have a ring tone. I don't care as much if it vibrates but just don't wa

  • Spry text fields "invisible" on ie6/ie7

    Hi, Attached is a screen shot of how spry text fields look in their initial state under ie6 and ie7 on a project at www.printingcommunication.com/wa/seattle/contact.html They are "invisible". I'm using Dreamweaver CS4 and spry 1.6.1. I have not made