Java Program to Check if a string is a valid shuffle of two distinct strings

To understand this example, you should have the knowledge of the following Java programming topics:


Example: Check if a string is a valid shuffle of two other strings

Output

1XY2 is a valid shuffle of XY and 12
Y1X2 is a valid shuffle of XY and 12     
Y21XX is not a valid shuffle of XY and 12

In the above example, we have a string array named results. It contains three strings: 1XY2, Y1X2, and Y21XX. We are checking if these three strings are valid shuffle of strings first(XY) and second(12).

Here, we have used 3 methods:

1. checkLength() - The number of characters in a shuffled string should be equal to the sum of the character in two strings.

So, this method checks if the length of the shuffled string is same as the sum of the length of the first and second strings.

If the length is not equal, there is no need to call the shuffleCheck() method. Hence, we have used the if statement as

// inside main method
if (checkLength(first, second, result) == true && shuffleCheck(first, second, result) == true)

2. sortString() - This method converts the string to char Array and then uses the Arrays.sort() method to sort the array. Finally, returns the sorted string.

Since we are comparing the shuffled string with the other two strings, sorting all three strings will make the comparison more efficient.

3. shuffleCheck() - This method compares the individual characters of the shuffled string with the characters of first and second strings