w3resource
Java Programming Exercies

Java String Exercises: Make a new string with each character of just before and after of t-string whichever it appears in m-string

Java String: Exercise-85 with Solution

Write a Java program to make a new string with each character of just before and after of t-string whichever it appears in m-string. Assume that m-string and non-empty t-string has given.

Sample Solution:

Java Code:

import java.util.*;
public class Main
{
public String mAndTstring(String m_stng, String t_stng) 
{
  int m_st_len = m_stng.length();
  int t_st_len = t_stng.length();
  String fin = "";
  for (int i = 0; i < m_st_len-t_st_len+1; i++) 
  {
    String tmp = m_stng.substring(i,i+t_st_len);
    if (i > 0 && tmp.equals(t_stng))
      fin += m_stng.substring(i-1,i);
    if (i < m_st_len-t_st_len && tmp.equals(t_stng))
      fin += m_stng.substring(i+t_st_len,i+t_st_len+1);
  }
  return fin;
}

public static void main (String[] args)
    {
      Main m= new Main();
      String str1 =  "weablcoabmeab";
      String str2 =  "ab";	  
      System.out.println("The given string are: "+str1+"  and "+str2);
      System.out.println("The new string is: "+m.mAndTstring(str1,str2));
	  }
}

Sample Output:

The given string are: weablcoabmeab  and ab
The new string is: elome

Flowchart:

Flowchart: Java String Exercises - Make a new string with each character of just before and after of t-string whichever it appears in m-string

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to make a new string made of p number of characters from the first of a given string and followed by p-1 number characters till the p is greater than zero.
Next: Write a Java program to return the number of triples in the given string. A triple is a character appearing three times in a row in a string.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming