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?



Java: Tips of the Day

Parsing dates:

import java.io.*;
import java.util.*;
import java.text.*;

String s = "2001/09/23 14:39";

SimpleDateFormat formatter = new SimpleDateFormat ("yyyy/MM/dd H:mm");
Date d = formatter.parse(s, new ParsePosition(0));