w3resource

Java: Test if a given string contains the specified sequence of char values


8. Contains Specified Sequence

Write a Java program to test if a given string contains the specified sequence of char values.

Visual Presentation:

Java String Exercises: Test if a given string contains the specified sequence of char values


Sample Solution:

Java Code:

// Define a public class named Exercise8.
public class Exercise8 {
    // Define the main method.
    public static void main(String[] args) {
        // Declare and initialize two string variables, str1 and str2.
        String str1 = "PHP Exercises and Python Exercises";
        String str2 = "and";
        
        // Print the original string.
        System.out.println("Original String: " + str1);
        // Print the specified sequence of char values.
        System.out.println("Specified sequence of char values: " + str2);
        
        // Check if str1 contains the sequence specified in str2 and print the result.
        System.out.println(str1.contains(str2));
    }
}

Sample Output:

Original String: PHP Exercises and Python Exercises                                                           
Specified sequence of char values: and                                                                        
true 

Flowchart:

Flowchart: Java String  Exercises - Test if a given string contains the specified sequence of char values


For more Practice: Solve these Related Problems:

  • Write a Java program to determine if a string contains a specified subsequence of characters in order.
  • Write a Java program to check if all characters of a given word appear in order within a larger string.
  • Write a Java program to verify whether a user-defined sequence of characters is present in a string, ignoring case.
  • Write a Java program to test if a string contains multiple specified substrings and display which ones are missing.

Go to:


PREV : Concatenate Two Strings.
NEXT : Compare with Char Sequence.

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.