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: 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 removing a specified character 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?

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