In: Computer Science
Using java: Write a class called StringAlternateSorting what it does: 1. ask user for one String (String1) (must be sorted) 2. ask user for second String (String2) (must be sorted) 3. Then prints all the characters of two previous Strings, in such a way that they are sorted (see examples below). 4. consider the possibility that strings are of different sizes, one or both can be empty, etc. 5. strings can contain any kind of characters as long as they are sorted
EXAMPLES
% java StringAlternateSorting.java enter first string: 1357 enter second string: 2468 12345678 % java StringAlternateSorting.java enter first string: 1 enter second string: 2345678 12345678 % java StringAlternateSorting.java enter first string: 23456 enter second string: 1 123456 % java StringAlternateSorting.java enter first string: 12345 enter second string: 9 123459 % java StringAlternateSorting.java enter first string: 9 enter second string: 12345 123459 % java StringAlternateSorting.java enter first string: 19 enter second string: 2345 123459 % java StringAlternateSorting.java enter first string: 2345 enter second string: 19 123459 % java StringAlternateSorting.java enter first string: enter second string: 12345 12345 % java StringAlternateSorting.java enter first string: 12345 enter second string: 12345 % java StringAlternateSorting.java enter first string: acef enter second string: bdghi abcdefghi % java StringAlternateSorting.java enter first string: 12345 enter second string: 13579 1123345579 %
ANSWER:-
CODE:-
import java.util.*;
class StringAlternateSorting{
public static String alternateSort(String s1, String
s2){
String out = "";
int i=0,j=0;
// length of first string
int len1 = s1.length();
// length of secong string
int len2 = s2.length();
while (i<len1 &&
j<len2) {
// characters of
both strings
char ch1 =
s1.charAt(i);
char ch2 =
s2.charAt(j);
// if character1
is less than
// character2
add it to out string
// and increase
i
// if character2
is less than
// character1
add it to out string
// and increase
j
if(ch1 <=
ch2){
out += ch1;
i++;
}else{
out += ch2;
j++;
}
}
// This is for handling
// different string length
// add remaining characters in
longer
// length string to out
string.
while (i<len1) {
out +=
s1.charAt(i++);
}
while (j<len2) {
out +=
s2.charAt(j++);
}
// return out string
return out;
}
public static void main(String[] args) {
Scanner sc = new
Scanner(System.in);
// Read strings from user.
System.out.print("enter first
string: ");
String s1 = sc.nextLine();
System.out.print("enter second
string: ");
String s2 = sc.nextLine();
// call alternateSort method
System.out.println(alternateSort(s1,s2));
}
}
NOTE:- If you need any modifications in the code,please commene below.Please give positive rating.THUMBS UP.
THANK YOU!!!!
OUTPUT:-
CODE SCREENSHOT:-