w3resource

Java Exercises: Accept two string and test if the second string contains the first one

Java Basic: Exercise-171 with Solution

Write a Java program to accept two string and test if the second string contains the first one.

Pictorial Presentation:

Java Basic Exercises: Accept two string and test if the second string contains the first one.

Sample Solution:

Java Code:

import java.util.*;
public class Solution {	
 public static boolean is_str_contains(String str1, String str2) {
    if (str1 == null || str2 == null) {
      throw new IllegalArgumentException("You can't pass null strings as input.");
    }
     boolean ans = false;
     for (int i = 0; i < str2.length() - 1; i++) {
       if (str2.charAt(i) == str1.charAt(0)) {
         for (int j = 0; j < str1.length(); j++) {
           if ((i + j) < str2.length() && str1.charAt(j) == str2.charAt(i + j) && j == str1.length() - 1) {
             ans = true;
             break;
           }
        }
      }
    }
    return ans;
  }

   public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Input first string: ");
		String str1 = scanner.nextLine();
		System.out.print("Input second string: ");
		String str2 = scanner.nextLine();
		System.out.println("If the second string contains the first one? "+is_str_contains(str1, str2));		
		}
}

Sample Output:

Input first string:  Once in a blue moon
Input second string:  See eye to eye
If the second string contains the first one? false

Flowchart:

Flowchart: Java exercises: Accept two string and test if the second string contains the first one.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to find the length of the longest consecutive sequence of a given array of integers.
Next: Write a Java program to get the number of element in a given array of integers that are smaller than the integer of another given array of integers.

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.

Java: Tips of the Day

Java: Anagrams

Generates all anagrams of a string.

public static List<String> anagrams(String input) {
    if (input.length() <= 2) {
        return input.length() == 2
                ? Arrays.asList(input, input.substring(1) + input.substring(0, 1))
                : Collections.singletonList(input);
    }
    return IntStream.range(0, input.length())
            .mapToObj(i -> new SimpleEntry<>(i, input.substring(i, i + 1)))
            .flatMap(entry ->
                    anagrams(input.substring(0, entry.getKey()) + input.substring(entry.getKey() + 1))
                            .stream()
                            .map(s -> entry.getValue() + s))
            .collect(Collectors.toList());
}

Ref: https://bit.ly/3rvAdAK