Sorting characters in a string into alphabetical order without arrays or maps (Java) -
i trying make program tests if 2 separate phrases anagrams of each other. this, want sort each string phrase alphabetical order , compare results. however, i want without using arrays or maps. far have pretty messy code/pseudocode:
import java.util.scanner; public class anagramcomparer{ public static void main(string[] args){ scanner scan = new scanner(system.in); system.out.println("enter sentence."); string sentence = scan.nextline(); sentence = sentence.tolowercase(); string empty1 = ""; for(int = 0; <= sentence.length(); i++){ //if char between 97 & 122 // if char <= charat (0 sentence length - x) if(sentence.charat(i) <= empty1.charat(0)){ empty1.replace(empty1.charat(0), sentence.charat(i)); } else{ empty1 = (empty1 + (sentence.charat(i))); } } system.out.println(empty1); system.out.println(sentence); } }
the idea here run through string sentence character-by-character , sort alphabetically in string empty1. feel free tell me if i'm going in wrong direction; appreciated.
strings immutable, empty1.replace
returns new string, doesn't modify existing one.
since string
uses char[]
internally, new string means new char[]
, you're still using arrays. might use own char[]
better performance , lower memory footprint.
char[] chars = sentence.tolowercase().tochararray(); arrays.sort(chars);
Comments
Post a Comment