In: Computer Science
public static java.lang.String mergeWithRuns(java.lang.String t, java.lang.String s)
Merges two strings together, using alternating characters from each, except that runs of the same character are kept together. For example,
Either or both of the strings may be empty. If the first string is nonempty, its first character will be first in the returned string.
Parameters:
t - first string
s - second string
Returns:
string obtained by merging characters from t and s, preserving runs
Explanation:
import java.io.*;
class Merging // Creating Main Class
{
// Creating and Implementing of method
public static java.lang.String mergePreservingRuns(java.lang.String t,java.lang.String s)
{
java.lang.String str=""; // Declare String variable str
int i=0,j=0; // Declare and Initialize two integer variables i and j
while(i<t.length() && j<s.length()) // Create while loop for two strings have characters left
{
char pChar=t.charAt(i++); // assign character by character to pChar
str+=pChar; // store into str
while(i<t.length() && t.charAt(i)==pChar) // This while loop for check equal characters until length of first string
{
str+=pChar; // then store character by character into str
i++;
}
// simillarly, second string
pChar=s.charAt(j++);
str+=pChar;
while(j<s.length()&&s.charAt(j)==pChar)
{
str+=pChar;
j++;
}
}
// the final string will be stored into the str of two string
while(i<t.length())
str+=t.charAt(i++);
while(j<s.length())
str+=t.charAt(j++);
return str; // this is resultant string to return
}
public static void main(String args[])
{
String s1,s2;
// call mergePreservingRuns() method
s1=mergePreservingRuns("abcde","xyz");
s2=mergePreservingRuns("abbbbcde", "xyzzz");
// print resultant strings
System.out.println("Merging two String alternative Characters: "+s1);
System.out.println("Merging two String alternative Characters: "+s2);
}
}
OUTPUT
F:\>javac Merging.java
F:\>java Merging
Merging two String alternative Characters: axbyczde
Merging two String alternative Characters: axbbbbyczzzde
...... Please like if it's helpfull for you and comment if any query...........