Java: Append two given strings such that, if the concatenation creates a double characters then omit one of the characters
56. Append Strings Without Double Characters
Write a Java program that appends two strings, omitting one character if the concatenation creates double characters.
Visual Presentation:
Sample Solution:
Java Code:
import java.util.*;
// Define a class named Main
public class Main {
// Method to concatenate two strings based on specific conditions
public String conCat(String st1, String st2) {
// Check if both strings are not empty and the last character of the first string matches the first character of the second string
if (st1.length() != 0 && st2.length() != 0 && st1.charAt(st1.length() - 1) == st2.charAt(0))
return st1 + st2.substring(1); // Concatenate the strings excluding the duplicate character
return st1 + st2; // If no match or empty strings, concatenate the strings as they are
}
// Main method to execute the program
public static void main(String[] args) {
Main m = new Main(); // Create an instance of the Main class
// Define two strings for concatenation
String str1 = "food";
String str2 = "door";
// Display the given strings and the concatenated string using the conCat method
System.out.println("The given strings are: " + str1 + " and " + str2);
System.out.println("The string after concatenation is: " + m.conCat(str1, str2));
}
}
Sample Output:
The given strings are: food and door The string after concatination are: foodoor
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Java program to concatenate two strings ensuring no duplicate characters occur at the junction point.
- Write a Java program to merge two strings while checking and removing any redundant adjacent characters.
- Write a Java program to append strings by eliminating overlapping character sequences at the boundary.
- Write a Java program to combine two strings with a condition to drop one character if the join produces consecutive duplicates.
Go to:
PREV : Remove Adjacent Duplicates Recursively.
NEXT : Swap Last Two Characters.
Java Code Editor:
Improve this sample solution and post your code through Disqus
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.