Contents

Check if it's a substring (with.Java)

   Nov 24, 2023     1 min read

This is the “Check if it’s a substring” problem.

We’re going to go through the process of solving a coding test problem, reflecting on the problem we solved, and learning about other ways to solve it.

Let’s start with the problem

The problem

A substring is a string that corresponds to a contiguous portion of a string.

For example, the strings “ana”, “ban”, “anana”, “banana”, and “n” are all substrings of the string “banana”, but “aaa”, “bnana”, and “wxyz” are not all substrings of “banana”.

Given the strings my_string and target as parameters, write a solution function that returns 1 if target is a substring of the string my_string and 0 otherwise.

Example input and output

my_stringtargetresult
“banana”“ana”1
“banana”“wxyz”0

My solution to the ### problem

class Solution {
    public int solution(String my_string, String target) {
        int answer = 0;
        if(my_string.contains(target)){
            answer = 1;
        }
    } return answer;
}

Solution Explanation

The contains method, which checks whether a string contains a target, is built into Java’s String class.

If my_string contains target as a substring, the character was solved by assigning 1 to answer.

See ####

The contains method is case sensitive, so you need to be careful.

If you want to ignore case and check for inclusion, you can do so after converting the string to all lowercase or all uppercase.