w3resource

Java String Exercises: Return the substring that is between the first and last appearance of the substring 'toast' in the given string, or return the empty string if substirng 'toast' does not exists

Java String: Exercise-69 with Solution

Write a Java program to return the substring that is between the first and last appearance of the substring 'toast' in the given string,or return the empty string if substirng 'toast' does not exists.

Sample Solution:

Java Code:

import java.util.*;
public class Main
{
public String pickMiddleOfBread(String stng) 
{
  int len = stng.length();
  String tmpString = "";
  String resultString = "";
  int st = 0;
  int en = 0;
  boolean found = false;
  if (len <= 10)
    return "";
  for (int i = 0; i < len - 4; i++) 
  {
    tmpString = stng.substring(i, i+5);
    if (tmpString.equals("toast") && found == true)
      en = i; 
    if (tmpString.equals("toast") && found == false) 
	{
      st = i+5;
      found = true;
    }
  }
  resultString = stng.substring(st,en);
  return resultString;
}
public static void main (String[] args)
    {
      Main m= new Main();
      String str1 =  "sweettoastbuttertoast";
      System.out.println("The given strings is: "+str1);
      System.out.println("The new string is: "+m.pickMiddleOfBread(str1));
	  }
}

Sample Output:

The given strings is: sweettoastbuttertoast
The new string is: butter

Pictorial Presentation:

Java String Exercises: Return the substring that is between the first and last appearance of the substring 'toast' in the given string,or return the empty string if substirng 'toast' does not exists

Flowchart:

Flowchart: Java String Exercises - Return the substring that is between the first and last appearance of the substring 'toast' in the given string,or return the empty string if substirng 'toast' does not exists

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to read a string and returns after remove the # and its immediate left and right characters.
Next: Write a Java program to check whether a string is pq-balanced or not. A String is pq-balanced if for all the p's in the string atleast one 'q' must exists right of the p's.But 'q' before the 'p' makes the pq-balanced false.

What is the difficulty level of this exercise?



Inviting useful, relevant, well-written and unique guest posts