Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Java String Exercises: 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 longer string and make them equal length.

Sample Solution:

Java Code:

import java.util.*;
public class Main
{
public String minCat(String st1, String st2) 
{
  if (st1.length() == st2.length())
    return st1+st2;
  if (st1.length() > st2.length())
  {
    int diff = st1.length() - st2.length();
    return st1.substring(diff, st1.length()) + st2;
  } else 
  {
    int diff = st2.length() - st1.length();
    return st1 + st2.substring(diff, st2.length());
  }
}
public static void main (String[] args)
    {
      Main m= new Main();
      String str1 =  "Welcome";
	  String str2 =  "home";
	  
      System.out.println("The given strings is: "+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

Pictorial Presentation:

Java String Exercises: Append two strings; remove characters from the beginning of longer string if the lengths of the string are different.

Flowchart:

Flowchart: Java String Exercises - Append two strings; remove characters from the beginning of longer string if the lengths of the string are different

Visualize Java code execution (Python Tutor):


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.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe