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

Similar Messages

  • 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

  • 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

  • Sort Comparator

    I have the following sort comparator that sorts x coordinates in ascending order.
                class ComparatorX implements java.util.Comparator
              public int compare( Object p1, Object p2) {
                   int x1=((Point)p1).x;
                   int x2=((Point)p2).x;
                   if(x1>x2) {
                                return 1;
                   if(x1<x2) {
                                return -1;
                   return 0;
         }I don't quite understand why this method sorts in ascending order...
    Can anyone enlighten me?

    I'm not sure if this is the answer you're look for but anyway....
    Sometimes, there are instances that you want to sort a list of objects that doesn't seem quite possible to be sorted. And by saying a list, that list is either a subclass of java.util.List or an array. Unlike a list of strings or a list of numbers, which we know it can be sorted alphabetically or by... well the numbers in either ascending or descending order, there are, sometimes, lists of objects that we want to sort in a particular manner.
    Assuming you have a list of customer account objects, which stores their account no and credit balance, and you want to sort them either by their account no or credit balance. Rather than writing your own algorithm to traverse the list and sort them, all you have to do is to implement 2 Comparators, one to sort by account no and the other by credit balance. Call the java.util.Collections.sort(List list, Comparator c) method by passing in your list and the desired comparator, and voila!, the list is sorted. The method needs a Comparator to tell it what the order of 2 given objects is, in order for it to perform a sort.

  • 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!!

  • How to compare string in a case-insensitive manner using JavaScript?

    Hello everyone,
    Now I have a javascript to compare checkbox's value with user's input, but now seems it only can compare case-sensitively, does some one know if there is a function in javascript that it can compare string case-insensitively ?
    Here is my script :
    function findOffice(field)
    var name;
    name=prompt("What is the office name?");
    var l = field.length;
    for(var i = 0; i < l; i++)
    if(field.value==name)
    field[i].checked=true;
    field[i].focus();
    field[i].select();
    break;
    <input type="button" name="Find" value="Find And Select" onClick="findOffice(form1) >
    Thanks in advance !
    Rachel

    Thank you so much, I already solved the problem with your advice.
    You really have a beautiful mind, :-).
    I appreciate your help !
    Rachel

  • Comparing string in select query

    Hi,
    select single *
           from mara
           where <b>matnr = wa-matnr</b>.
    Here matnr is char18. Can we compare string like this?
    When <b>wa-matnr</b> is in <b>lower case</b> it is setting sy-subrc = 4, even though the matnr exists in mara. When converted to upper case and used it is setting sy-subrc = 0.
    Is there any other solution for the problem? I have checked out with matnr's conversion routine. It is also not working.

    just try  dat way...
    <b>ex...</b>
    data:wa_matnr like mara-matnr.
    data:wa_matnr1 like mara-matnr.
    data: gv_matnr like mara-matnr.
    wa_matnr = 'comptest'.
    CALL FUNCTION 'TERM_TRANSLATE_TO_UPPER_CASE'
      EXPORTING
       LANGU                     = SY-LANGU
        TEXT                     = wa_matnr
    IMPORTING
       TEXT_UC                   = wa_matnr1
    EXCEPTIONS
      NO_LOCALE_AVAILABLE       = 1
      OTHERS                    = 2
    IF SY-SUBRC <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
            WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    select single matnr
    from mara into gv_matnr
    where matnr = wa_matnr or matnr = wa_matnr1.
    write : gv_matnr.

  • 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

  • Public static final Comparator String CASE_INSENSITIVE_ORDER

    in this declaration..
    public static final Comparator<String> CASE_INSENSITIVE_ORDER
    what does <String> mean?
    thanks!

    what does the Comparator do. Look at the API and you would see the following description about the compare method.
    public int compare(Object o1,
    Object o2)Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
    The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y. (This implies that compare(x, y) must throw an exception if and only if compare(y, x) throws an exception.)
    The implementor must also ensure that the relation is transitive: ((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0.
    Finally, the implementer must ensure that compare(x, y)==0 implies that sgn(compare(x, z))==sgn(compare(y, z)) for all z.
    It is generally the case, but not strictly required that (compare(x, y)==0) == (x.equals(y)). Generally speaking, any comparator that violates this condition should clearly indicate this fact. The recommended language is "Note: this comparator imposes orderings that are inconsistent with equals."
    Now your question is about what <String> is in your declaration. It is the type of the objects which are going to be compared.

  • Compare Strings using JSTL

    How can I compare strings with JSTL? One string is a stored date and the other is a generated date. My goal is to set the correct date in a dropdown menu with date values (yyyy-MM-dd) by comparing the current date with the stored.
    Code
    <%
    Calendar cal = Calendar.getInstance(timezone, locale);
    Format fm = new SimpleDateFormat("yyyy-MM-dd");
    String date2 = (String) fm.format(cal.getTime()); %>
    <c:set var="date1" value="${mb.date}" />   // from database lookup (MySQL Date)
    <p><c:out value="${date1}"/>=<%=date2%>:<c:out value="${date1 == '<%=date2%>' }" /></p>The result is:
    2004-08-03 = 2004-08-03 : false

    well, about this:
    <%
    Calendar cal = Calendar.getInstance(timezone, locale);
    Format fm = new SimpleDateFormat("yyyy-MM-dd");
    String date2 = (String) fm.format(cal.getTime());
    pageContext.setAttribute("date2",date2);
    %>
    <c:set var="date1" value="${mb.date}" />   // from database lookup (MySQL Date)
    <p><c:out value="${date1}"/> .equals <%=date2%>:<c:out value="${date1eq date2}" /></p>I try to use the EL 'eq' like you would use '.equals()' in regular java, and EL '==' like regular java '==' And since we are comparing Strings here, which are objects, we would use .equals rather than ==, since == compares refernce and .equals compares value...

  • Simple question - compare Strings with SSIS expression language

    SSIS variables - strOne = YES, strTwo = YES. I want to compare strings using ssis expression language (ie inside a variable's expression box, constraint of task flow arrow etc).
    Will @strOne == @strTwo be true ? I hope its not like programming languages where you need to do
    @strOne.Equals(@strTwo) instead of ==. Also is @strOne == "YES" true ?

    ([User::strOne] == [User::Strtwo] ? True : False)
    The third variable created should be of type boolean if you're using above expression. if its of type int return 0 and 1 instead of False and true
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Compare string in different line in text file

    I am new to java and I need a simple example to compare string in file text by for loop
    file.txt:
    A78802 D06VAIS060253113 WKNEUP751346577450
    A77802 D06VAIS060253113 WKNEUP751346577450
    A76802 D06VAIS060253925 WKNEUP751346577450
    A78802 D06VAIS075253698 WKNEGE226375082796
    A73802 D06VAIS116253222 WKNEFB227345305299
    dataString = TextIO.getln();
    A=dataString.substring(25,42);
    B=dataString.substring(195,203);
    C=dataString.substring(171,186);
    I WANT COPMPARE IN LINE 1 POSITION 20 TO LINE 2 POSITION 20 BY LOOPS ALL THE LINE IN TEXT FILE

    what have you tried so far?
    Also, when posting your code, please use code tags so that your code will retain its formatting and be readable. To do this, either use the "code" button at the top of the forum Message editor or place the tag &#91;code] at the top of your block of code and the tag &#91;/code] at the bottom, like so:
    &#91;code]
      // your code block goes here.
    &#91;/code]

  • Compare string in JSTL

    Hi all,
    I have   <c:set var="status" value="${found.studentStatus}"/> inside loopI want to call it outside the loop and compare string
    <c:if test="${status.equals("A")}">
    do something
    </c:if>
    But I get bug equals symbol expect, what is wrong?

    EL is not java. The same rules don't apply. You actually do want to use the equals operator here. It ends up invoking the java .equals method in the end.
    To make it explicit:
    <c:if test="${status == 'A'}">
    //or
    <c:if test="${status eq 'A'}">Cheers,
    evnafets

  • 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?

  • C:choose for comparing strings

    Hi,
    I am trying to apply alternate styles to table rows using JSTL. When I am comparing strings it always falls into the 'otherwise' block. I guess I either have a silly error or there is something I am missing. When I output the string with the c:out it is set to the value 'data_row_white', which is what I find confusing as the test should prove true.
    I have also tried using the 'eq' operator to compare.
    Any help is appreciated.
    <c:set var="col_css" scope="page" value="data_row_white" />
            <c:forEach items="${requestScope['local_catalogue_list']}" var="item">
                <tr class="${col_css}">
                    <td class="no_top_no_right"><a href="javascript:viewCatalogue('${item.catalogueID}');">${item.catalogueName}</a></td>
                    <td class="no_top_middle">${item.status}</td>
                    <td class="no_top_no_left">${item.versionID}</td>
                </tr>
                <c:out value="${col_css}" />
                <c:choose>               
                    <c:when test="${col_css == 'data_row_white'} ">
                        <c:set var="col_css" scope="page" value="data_row_gray" />
                    </c:when>
                    <c:otherwise>                   
                        <c:set var="col_css" scope="page" value="data_row_white" />
                    </c:otherwise>
                </c:choose>
            </c:forEach>

    Using the ternary operator in EL which intercepts on the loop index is a much better/clearer/quickier way to alternate table rows.
    Basic example:    <table>
            <c:forEach items="${users}" var="user" varStatus="loop">
                <tr class="${loop.index % 2 == 0 ? 'even' : 'odd'}">
                    <td>${user.id}</td>
                    <td>${user.username}</td>
                    <td>${user.email}</td>
                    <td>${user.age}</td>
                </tr>
            </c:forEach>
        </table>

Maybe you are looking for

  • Memory on the iphone

    Sounds like a dumb questions, but I'm assuming the only thing that takes up the memory on the phone is music, etc. Contact are put on the sim card that is separate memory? Pleae correct me if i'm wrong. Thanks

  • How to avoid creation of _(file.*), coping from tiger to pc?

    how to avoid the creation of this file for ever on a pc environment?? I explain: as i copy any image file, it goes to a spooler directory and that begins instantly to process the file to an OPI server, separating CMYK channels, converting it to high

  • Installing Windows 7 Upgrade Edition on a new Macbook Pro

    Hi all, I am a recent convert to Apple after becoming more and more disillusioned with Windows for the past 10 or so years. I have ordered a shiny new 15" 2011 MBP and can't wait for it to arrive! My issue is that I am going to need to install Window

  • Satellite L300D-12U - Two issues after Ubuntu Linux installation

    Hello, I have installed Ubuntu 8.10 on my brand new Satellite L300D-12 U. Up to now everything works fine but there are two things disturbing me. 1. I have problem with Suspend to RAM. It does not work. If I use the standby option, the screen becomes

  • Embed YouTube video into SCORM (HTML5) using Captivate 7?

    Hi there, I am using Captivate 7 to produce a SCORM compliant HTML5 course - this course includes a video, however when I have tried to upload the video directly, it pauses/doesn't play well in our LMS.  As such I wanted to try embedding/streaming th