SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
Recursion
Exercise:
Programming Projects
Question:8 | ISBN:9780132830317 | Edition: 5

Question

Write a recursive method named contains with the following header:

public static boolean contains(String haystack, String needle)

The method should return true if needle is contained within haystack and false if needle is not in haystack . For example,

contains("Java programming", "ogr") should return true

contains("Java programming", "grammy") should return false

You are not allowed to use the substring method to find a match.


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

PROGRAM CODE:

public class Main {
    public static boolean contains(String haystack, String needle) {
        if (needle.length() == 0) {
            return true;  // An empty string is always contained within any string
        }

        if (haystack.length() < needle.length()) {
            return false;  // The needle is longer than the remaining haystack, so it can't be found
        }

        if (haystack.charAt(0) == needle.charAt(0)) {
            // The first characters match, check the remaining characters
            if (contains(haystack.substring(1), needle.substring(1))) {
                return true;  // Found a match
            }
        }

        // Move to the next character in the haystack and try again
        return contains(haystack.substring(1), needle);
    }

    public static void main(String[] args) {
        String haystack = "Java programming";
        String needle1 = "ogr";
        String needle2 = "grammy";

        System.out.println(contains(haystack, needle1));  // true
        System.out.println(contains(haystack, needle2));  // false
    }
}

 

OUTPUT OF THE PROGRAM CODE:

true
false

 

0 0

Discussions

Post the discussion to improve the above solution.