w3resource

Java: Return true if a given string contain the string 'pop', but the middle 'o' also may other character


72. Contains P?P Pattern

Write a Java program to return true if a given string contains the string 'pop', but the middle 'o' also may contain another character.

Visual Presentation:

Java String Exercises: Return true if a given string contain the string 'pop', but the middle 'o' also may other character


Sample Solution:

Java Code:

import java.util.*;

// Define a class named Main
public class Main {

    // Method to check if "p?p" pattern appears in the given string
    public boolean popInTheString(String stng) {
        int len = stng.length(); // Get the length of the input string

        // Iterate through the string up to the third-to-last character
        for (int i = 0; i < len - 2; i++) {
            // Check if the current character is 'p' and the character two positions ahead is also 'p'
            if (stng.charAt(i) == 'p' && stng.charAt(i + 2) == 'p') {
                return true; // Return true if "p?p" pattern is found
            }
        }
        return false; // Return false if the pattern is not found in the string
    }

    // Main method to execute the program
    public static void main(String[] args) {
        Main m = new Main(); // Create an instance of the Main class

        String str1 = "dikchapop"; // Input string to be checked

        // Display the given string and check if "p?p" pattern appears in the string using popInTheString method
        System.out.println("The given string is: " + str1);
        System.out.println("Does 'p?p' appear in the given string? " + m.popInTheString(str1));
    }
}

Sample Output:

The given string is: dikchapop
Is p?p appear in the given string? true

The given string is: dikp$pdik
Is p?p appear in the given string? true

Flowchart:

Flowchart: Java String Exercises - Return true if a given string contain the string 'pop', but the middle 'o' also may other character



For more Practice: Solve these Related Problems:

  • Write a Java program to detect occurrences of the pattern "p?p" where '?' can be any character.
  • Write a Java program to check for a pattern that starts with 'p', has any character, and ends with 'p'.
  • Write a Java program to verify if a string contains a flexible "pop" pattern allowing a wildcard in the middle.
  • Write a Java program to identify and return true if a string contains a substring matching "p?p" using regex.

Go to:


PREV : One String at End of Other.
NEXT : Substring Before Period.

Java Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.