Java: Append two strings; remove characters from the beginning of longer string if the lengths of the string are different
Java String: Exercise-60 with Solution
Write a Java program to read two strings append them together and return the result. If the strings are different lengths, remove characters from the beginning of the longer string and make them equal lengths.
Visual Presentation:
Sample Solution:
Java Code:
import java.util.*;
// Define a class named Main
public class Main {
// Method to concatenate two strings while ensuring the minimum length
public String minCat(String st1, String st2) {
// Check if the lengths of the strings are equal
if (st1.length() == st2.length())
return st1 + st2; // If equal, concatenate the strings directly
// Check if the length of the first string is greater than the length of the second string
if (st1.length() > st2.length()) {
int diff = st1.length() - st2.length(); // Calculate the length difference
return st1.substring(diff, st1.length()) + st2; // Concatenate with adjusted lengths
} else {
int diff = st2.length() - st1.length(); // Calculate the length difference
return st1 + st2.substring(diff, st2.length()); // Concatenate with adjusted lengths
}
}
// Main method to execute the program
public static void main(String[] args) {
Main m = new Main(); // Create an instance of the Main class
String str1 = "Welcome"; // First string
String str2 = "home"; // Second string
// Display the given strings and the new concatenated string using the minCat method
System.out.println("The given strings are: " + str1 + " and " + str2);
System.out.println("The new string is: " + m.minCat(str1, str2));
}
}
Sample Output:
The given strings is: Welcome and home The new string is: comehome
Flowchart:
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a Java program to read a string,if the string begins with "red" or "black" return that color string, otherwise return the empty string.
Next: Write a Java program to create a new string taking specified number of characters from first and last position of a given string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/java-exercises/string/java-string-exercise-60.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics