Results 1 to 4 of 4

Thread: sort string

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Jun 2005
    Posts
    1,170

    sort string

    Hello, I am trying to write a simple sort string without using the array sort method. But it's not working. please help

    Code:
     public static String sort(String s) {
        	StringBuffer s1 = new StringBuffer(s);
        	s1.sort();
        	return s1.toString();
        }

  2. #2
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: sort string

    I don't know what you are trying to achieve. But here is some code that uses a simple buble sort
    Code:
        public static String sort(String string)
        {
            for(int i=0;i<string.length()-1;i++)
                for(int j=i+1;j<string.length();j++)
                    if(Character.toLowerCase(string.charAt(j))<Character.toLowerCase(string.charAt(i)))
                        string = swap(string,i,j);
            return string;
        }
        
        private static String swap(String s, int i, int j)
        {
            char[] chars=s.toCharArray();
            char tmp=chars[i];
            chars[i]=chars[j];
            chars[j]=tmp;
            return new String(chars);
        }
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

  3. #3

    Thread Starter
    Frenzied Member
    Join Date
    Jun 2005
    Posts
    1,170

    Re: sort string

    Hello, yeah it works. but could you explain to me about the code below? I could not get it at all, especially with 2 dimensional arrays:

    Code:
    private static String swap(String s, int i, int j)
        {
            char[] chars=s.toCharArray();
            char tmp=chars[i];
            chars[i]=chars[j];
            chars[j]=tmp;
            return new String(chars);
        }

  4. #4
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: sort string

    Code:
    private static String swap(String s, int i, int j)
        {
            // Convert String to char array
            char[] chars=s.toCharArray();
            // store char number i in temporary variable
            char tmp=chars[i];
            // replace char[i] with char[j]
            chars[i]=chars[j];
            // replace char [j] with the temp value (old i value)
            chars[j]=tmp;
            // Return a new string from the partially sorted char array
            return new String(chars);
        }
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width