How can I swap two characters in a String
? For example, \"abcde\"
will become \"bacde\"
.
//this is a very basic way of how to order a string alpha-wise, this does not use anything fancy and is great for school use
package string_sorter;
public class String_Sorter {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String word = "jihgfedcba";
for (int endOfString = word.length(); endOfString > 0; endOfString--) {
int largestWord = word.charAt(0);
int location = 0;
for (int index = 0; index < endOfString; index++) {
if (word.charAt(index) > largestWord) {
largestWord = word.charAt(index);
location = index;
}
}
if (location < endOfString - 1) {
String newString = word.substring(0, location) + word.charAt(endOfString - 1) + word.substring(location + 1, endOfString - 1) + word.charAt(location);
word = newString;
}
System.out.println(word);
}
System.out.println(word);
}
}