Sorting String Question

Hi guys, I'm still learning the intricacy of Java at the moment so bear with me, as I'm sure the answer is going to be simple has heck ...
I'm trying to sort a String, where I can make the letters in order. Basically, if the String is "ddeab" then it should be converted to "abdde".
So far, I'm using an int variable to get the value of the char in first and second letter ( via charAt to pick the position ) and swap them if they're are lower. However, this is where I'm stuck - how do I get them to "swap" in a string?
Edited by: Phoom on Dec 1, 2007 11:58 AM

Phoom wrote:
After a quick reading on Strings, I found toCharArray() useful in this case. I guess I can convert it back to string format by using a for loop and make it add to a string.
...No need to loop over that array: have a look at the various constructors of the String class.
And unless it a (homework) requirement to implement your own sorting algorithm, have a look at java.util.Arrays' sort methods.
Good luck.

Similar Messages

  • Looking to Search and Sort String Twice, though am having issues

    I am inputing from an access file a test library, the files in the access file are out of alphabetical order...thus I search and sort and bring these into LV in alphabetical order.  But I am running into the issue of trying to further search and sort the second column of info via the model number:
    example:
    Model ............. Model #
    Zetor               55
    Challenger        55
    Ford                55
    Zetor               66
    Challenger        66
    Ford                 66
    Zetor               45
    Challenger        45
    Ford                45
    Zetor               96
    Challenger        96
    Ford                 96
    Need to Return the Files as per below:
    Zetor               45
    Challenger        45
    Ford                45
    Zetor               55
    Challenger        55
    Ford                55
    Zetor               66
    Challenger        66
    Ford                 66
    Zetor               96
    Challenger        96
    Ford                 96
    Attachments:
    search & sort string.JPG ‏65 KB

    actually in my original post I had a brain-lapse on what the final sort needed to be....
    I was looking for this:
    Challenger        45
    Challenger        55
    Challenger        66
    Challenger        96 Ford                 45
    Ford                 55
    Ford                 66
    Ford                 96
    Zetor                45
    Zetor                55
    Zetor                66
    Zetor                96
     thanks for the quick response.

  • [C] Trying to sort string into reverse order ... Blank. [SOLVED]

    Here are the pre-processors:
    #include <stdio.h>
    #include <string.h>
    Here are the global variables:
    char output[999];
    Here's the function to sort string to reverse order (I THINK THE PROBLEM IS HERE):
    char output[999];
    char *sort_reverse(const char *str)
    int i, j = 0;
    for (i = strlen(str); i > 0; i--)
    output[j] = str[i];
    j++;
    return output;
    And, function int main(void):
    int main(void)
    printf("Reverse of \"Hello\": %s\n", sort_reverse("Hello"));
    return 0;
    The output is:
    Reverse of "Hello":
    Why is that? how can i fix that?
    Last edited by milo64 (2013-03-28 01:45:46)

    Instead of the global char output[999] wich is really big, you could allocate a perfectly sized array with calloc - like this in the sort_reverse function:
    char *output = calloc(strlen(input_string), sizeof(char));
    and in main program:
    char *reversed_string = sort_reverse("Whatever");
    printf("%s\n", reversed_string);
    //Remember to free reversed_string with
    free(reversed_string);
    //Since its allocated in the heap with calloc()
    Try check man-page for calloc, it will zero out the bytes aswell, then you wont have to worry about setting the last element to '\0'.
    NOTE: you have to iterate with "strlen(input_string) - 1" otherwise you will overwrite the needed '\0'
    EDIT:  As strlen excludes the '\0' in original string, then you have to make space for that by adding one to strlen return value so:
    char *output = calloc(strlen(input_string) + 1, sizeof(char));
    Last edited by Boogie (2013-04-05 09:46:12)

  • Sort strings. How to make it case-insensitive?

    I wish to sort some String objects. TreeSet does it automatically, but letters are case-sensitive. Is there some static method that sorts Strings without regard to letter cases, so that "String B" will come between "String b" and "String C"?

    SortedSet mySet = new TreeSet(String.CASE_INSENSITIVE_ORDER);
    mySet.add("monkey");
    mySet.add("Zebra");
    mySet.add("Aardvark");
    for(Iterator i = mySet.iterator(); i.hasNext(); ) {
      System.out.println(i.next());
    }I think you probably could have figured that out by looking at the API.

  • Sort String Field Mandatory in Production Order Components Screen

    Hi Gurus,
    Am currently working on ECC 6.0 environment.
    When I try to assign a batch to the components of the production order, the 'Sort String' is a mandatory field.
    Can you please suggest from where is this mandatory field is picked? Is it possible to populate the field automatically? Or how to make the 'Sort String' field not mandatory?
    In order type parameters (OPL8), standard parameters for display profiles are maintained.
    Have also tried to maintain user parameters like F1F, S3F and S5F without success.
    Your guidance please.
    Thanks in advance.
    The above mentioned problem does not occur if I try to create production order without reference of planned order using T Code CO01. This problem occurs only when I am converting planned order to production order.
    Note that have tried maintaining sort string in the BoM. The sort string gets picked up when am creating manual production orders. Not copied when converting planned orders to production orders.
    Tarang
    Edited by: Tarang Machhar on Sep 28, 2010 7:23 PM
    Edited by: Tarang Machhar on Sep 28, 2010 7:28 PM

    Hi Tarang,
    I think there is a transaction/screen variant maintained for that. Ask your ABAP team member to debug and check if there is any coding done to make it mandatory. There is no customizing for this one. There must be some code written to make it mandatory.
    But you are correct, if you maintain the sort string in BOM, it gets copied on to the planned order, the reservation and the production order as well.
    Regards,
    Pradeep.

  • Sorting string by first character

    What is the easiest way to sort strings by the first character?  I can sort by a complete string match, but what I really want to do is just sort by the first letter of character.  Is there a way to do something like a reverse concatenate?  
    Thank you
    Danny
    Danny
    Attachments:
    Sort string.vi ‏11 KB

    This is one of those times where I think Regular Expressions can be of use.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines
    Attachments:
    Sort string_BD.png ‏26 KB

  • Sort String

    Hello,
    Someone asked me about the fiel Sort String in a BOM. I have seen it in a BOM layout but never know how this works and how to use it. I've read a little about it but not confident that I grasp a full understanding of it.
    Could somebody please explain how this field is used and the benefits of using it? I would appreciate it if you could present a concrete example  with a step by step so I could comprehend it well.
    Thanks,
    GIE

    I guess you're new to the forums, so in future use the search feature & you should find most of the queries asked earlier, as in this case.
    To keep it simple its a field which you can use for sorting. Normally the sorting is done based on the item nos. so in many cases you might want to sort the components not just based on item nos. or material nos. but based on some logical connection between the components. So in that case you can specify the string and sort based on this column.
    The benefit if I can say so is, it helps in visualization. Anyway the best way to understand is go to CS02, open some BOM in edit mode, maintain some sort strings, follow menu path Edit -> Sort -> Sort by sort string & check the results.

  • Sorting string like windows file name sorting

    Hi everybody, I have a simple question.
    I was trying to sort some file name in java
    Let say we have a list of string which are :
    1.txt
    a.txt
    2.txt
    11.txt
    a(1).txt
    a(11).txt
    a(2).txt
    If i convert those strings as file names, and sort it by file name in the windows explorer the result is
    1.txt
    2.txt
    11.txt
    a(1).txt
    a(2).txt
    a(11).txt
    a.txt
    But if i enter those strings into an Arraylist and use Arrays.sort or Collections.sort, the result is
    1.txt
    11.txt
    2.txt
    a(1).txt
    a(11).txt
    a(2).txt
    a.txt
    Is there a way to achieve the string sort similar to windows rather than aplhabetically like the default sort of Arrays/Collection.
    I have done some searching but only found problem regarding to different language character sorting which can be achieved using Collator but this was not my case. Has anybody encounter this issue ?
    Any help is greatly appreciated
    regards
    Hendra Effendi

    ballistic_realm wrote:
    Let say we have a list of string which are :
    1.txt
    a.txt
    2.txt
    11.txt
    a(1).txt
    a(11).txt
    a(2).txt
    If i convert those strings as file names, and sort it by file name in the windows explorer the result is
    1.txt
    2.txt
    11.txt
    a(1).txt
    a(2).txt
    a(11).txt
    a.txt
    ...Not sure, but wouldn't Windows sort it like:
    1.txt
    2.txt
    11.txt
    a.txt
    a(1).txt
    a(2).txt
    a(11).txt
    If so, the try something like this (UNTESTED!):
    class WindowsFileNamesComparator implements Comparator<String> {
        public int compare(String a, String b) {
            String[] tokensA = tokenize(withoutExtension(a));
            String[] tokensB = tokenize(withoutExtension(b));
            int max = Math.min(tokensA.length, tokensB.length);
            for(int i = 0; i < max; i++) {
                if(tokensA.equalsIgnoreCase(tokensB[i]))
    continue;
    else if(tokensA[i].matches("\\d+") && tokensB[i].matches("\\D+"))
    return -1;
    else if(tokensA[i].matches("\\D+") && tokensB[i].matches("\\d+"))
    return 1;
    else if(tokensA[i].matches("\\d+") && tokensB[i].matches("\\d+"))
    return Integer.valueOf(tokensA[i])-Integer.valueOf(tokensB[i]);
    else
    return tokensA[i].compareTo(tokensB[i]);
    return tokensA.length - tokensB.length;
    private String[] tokenize(String s) {
    List<String> tokens = new ArrayList<String>();
    Matcher m = Pattern.compile("\\d+|\\D+").matcher(s);
    while(m.find()) {
    tokens.add(m.group());
    return tokens.toArray(new String[]{});
    private String withoutExtension(String s) {
    int lastDot = s.lastIndexOf('.');
    return lastDot < 0 ? s : s.substring(0, lastDot);

  • Sorting String Value

    Hi All,
    i have a simple question but don't know how to resolve it
    i have some files with name like abc_15-06-09 we need to sort these file based on the time stamp appended at the end of the file, in my example "15-06-09"
    i am not sure how can i sort these string value provided i can just take these time stamp from the file using sub-string.i need to sort these file based on the stamp old time stamp will get preference
    any help in this regard wil be mcuh appricaited
    thnaks in advance,
    umesh

    umesh_awasthi wrote:
    try
    Date today;
    ArrayList<Date> datetoComp=new ArrayList<Date>();
    today = df.parse("12/10/2009/12/34/18");
    datetoComp.add(today);
    today = df.parse("12/10/2008/12/34/18");
    datetoComp.add(today);
    today = df.parse("12/10/2009/12/34/18");
    datetoComp.add(today);
    today = df.parse("11/10/2009/12/34/18");
    datetoComp.add(today);
    today = df.parse("12/10/2009/12/34/18");
    datetoComp.add(today);
    System.out.println(datetoComp.size());
    Collections.sort(datetoComp);
    for (Iterator i = datetoComp.iterator(); i.hasNext();)
              Date currentDate = (Date) i.next();
              System.out.println(currentDate);
    } catch (ParseException e)
    Result:
    Sat Jan 12 00:34:18 IST 2008
    Sun Jan 11 00:34:18 IST 2009
    Mon Jan 12 00:34:18 IST 2009
    Mon Jan 12 00:34:18 IST 2009
    Mon Jan 12 00:34:18 IST 2009
    not as expectedfirst learn to put your code in [{}{code}] format.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Sort string by length

    Hi Everyone
    I have a set of data
    qqq
    adadada as
    aas a
    asada
    adasdas adada
    now I need a formula which can sort these strings according to the length. So the longest string will come at the top. I would really appreciate if anyone could help me with it.
    Thanks

    If you need to code this yourself then simply implement a sorting algorithm, get the two lengths and swap the Strings if necessary.
    If you can utilise the sort method written in Collections class, then you will need to write your own Comparator.
    Read about these classes and try it yourself. If you are still having trouble come back and ask a specific question.

  • Moving Multiple Albums & Album Sort Order Questions

    Hopefully this is a really easy question to answer, but I just can't figure out how to do this.
    1. Can you move multiple albums around in Aperture? I just imported my iPhoto libraries and I'd like to groups a set of the albums that I have into one project. The problem is that I can only move one album at a time.
    2. Can you specify the sort order or manual set the order that albums appear in projects or folders? It seems that Aperture automatically sorts them alphabetically.
    Thanks!

    1. Can you move multiple albums around in Aperture?
    unfortuantely, as far as i am aware you can only move one at a time
    2. Can you specify the sort order or manual set the
    order that albums appear in projects or folders? It
    seems that Aperture automatically sorts them
    alphabetically.
    you are correct, automatically alphabetically only ... i haven't been abble to change this at all ... the only way to force something else is by adding a ~ or other character that is ahead of 0 ...

  • String question

    is there a way to remove a character from a string, for example:
    "< head>"
    and do some sort of trim to it to create
    "<head>"
    thanks

    halfpipehippie wrote:
    is there a way to remove a character from a string, for example:
    "< head>"
    and do some sort of trim to it to create
    "<head>"
    thanksreplaceAll(...) can handle this quite easily:
    String text = "abc <head > def </ head > ghi";
    System.out.println(text.replaceAll("\\s++(?=[^<>]*+>)", ""));But when your tags contain attributes, you can't use the code above. But, you would have mentioned such an important piece of information in your original post, right?

  • Two String questions

    Hi!
    I have two questions:
    1) Can I do toString() on a null value?
    2) Is there any difference in writing:
    String s = new String();
    and
    String s;

    isnt it true that in the first case s -object of
    String class is created??Yes, the empty string, length zero, as he said.
    >
    in second case just defining a variable type String??Yes. It will either be null or have an udefined value, depending on whether it's a member variable or a method variable.

  • Question being asked multiple times but need to sort the questions into the report

    question needs to be placed 150 times on the form, but needs to be sorted as if it were one question on the report

    Hello seaturtles24
    Check out the article below for repeated requests for authorizations in iTunes.
    iTunes repeatedly prompts to authorize computer to play iTunes Store purchases
    http://support.apple.com/kb/ts1389
    Regards,
    -Norm G.

  • Convert string question... "\"

    I try the below code on jsp, but result is : a , a\b
    but I want the result is : a\\b, a\\\\b
    Thanks !
    <%
         String str = "a\b, a\\b";
         String outStr = "";
         for (int i=0;i<str.length();i++){
              char c = str.charAt(i);
              if (c == '\\'){
                   outStr += "\\";
              else{
                   outStr += c;
    %>
    <%=outStr%>

    Right, because the compiler interprets "\\" as an escape character, indicating that you want a backslash. (If you tried to just use a String "\", you'd probably get a compilation error, since the compiler would think you were trying to escape the second quotation).
    I think you're going to need to use RegExp... this question has been asked a bunch before, so search through the forums for an answer.

Maybe you are looking for