itsaferbie
itsaferbie

Reputation: 81

Sort a string in alphabetical order without arrays in java

What I need to do is take a string that has random letters and take the letters and put them in alphabetical order. For example, lidfj, would be; dfijl.

What I am having trouble figuring out is how I should start the code. I know that I may need to use compare to, since I am not allowed to use arrays, but I'm not sure if that would be the best approach. And I'm not sure how I would start that either.

Thanks in advance.

Edit: I think I'm done for the night, since I can't seem to think of anything else.

public class PP426 {
    public static String alphabetize (String input) {
        String sorted = ";
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if () {
                sorted += character;
            }
        }

        return sorted;

    }
    public static void main(String[] args) {
        System.out.println(alphabetize("iunaselfksdf"));
    }
}

Upvotes: 1

Views: 8992

Answers (2)

Adrian Shum
Adrian Shum

Reputation: 40036

From your questions and comments, seems that it is a homework assignment, for which you are allowed to use only String class for sorting (it is obviously not efficient but... well... it is a homework anyway).

Here I assume you already have idea on how to do sorting (e.g. bubble sort) with array. If not, search for the simplest sorting algorithm like insertion sort and learn it.

If you know how to sort with an array, you can simply translate your logic to use String's methods.

For example:

  • accessing character at position: yourString.charAt(i)
  • setting character at position: yourString = yourString.substring(0, i) + charToSet + yourString.substring(i+1)
  • appending a character: yourString += charToSet

If you don't even have knowledge in sorting, here is one method that works which involves only String:

I am not going to give you actual code. Learn it by yourself:

for currentChar in 'a' to 'z'
  loop through each char in inputString
    if you encounter any char = currentChar then 
       append that character to resultString
    end if 
  end loop
end for

resultString contains the result you need

Upvotes: 5

Johannes H.
Johannes H.

Reputation: 6167

Use a for loop and String.charAt() to traverse the string. Use a StringBuilder (for efficiency, concatenating Strings works as well but is meh performance wise) to assemble the letters in the order. WIth this knowledge, now implement you preferred sorting algorithm (which, I guess, is part of the excersise, so I won't do it here ;) )

Upvotes: 2

Related Questions