Java add code in ??? Take a non-empty string composed only of letters \'A\' to \
ID: 3867089 • Letter: J
Question
Java add code in ???
Take a non-empty string composed only of letters 'A' to 'H' and the EMPTY_CHAR ('.'), and return a new string that contains only the letters, with the letters sorted. The number of each letter must be exactly the same, no spaces or any other character should appear, and the letters must be sorted lexicographically Examples: in: "A.B...A.C." out: "AABC" in: "....CC..CA.F." out: "ACCCF"
convert from String to array of char using toCharArray(), and then do your work using the char array before converting back by creating a new String with the char array as the argument to the constructor
public static String numberString(String in) { ???? return in; }
Explanation / Answer
import java.util.Arrays;
public class SortArrLex {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("A.B...A.C.--> " + numberString("A.B...A.C."));
System.out.println("....CC..CA.F.--> " + numberString("....CC..CA.F."));
}
/**
*
* @param in
* @return
*/
public static String numberString(String in) {
char[] charArr = in.toCharArray();
char[] lettArr = new char[in.length()];
for (int i = 0, j = 0; i < charArr.length; i++) {
if (charArr[i] >= 'A' && charArr[i] <= 'H') {
lettArr[j] = charArr[i];
j++;
}
}
Arrays.sort(lettArr);
return new String(lettArr).trim();
}
}
OUTPUT:
A.B...A.C.-->AABC
....CC..CA.F.-->ACCCF
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.