Contents

Count how many times a string occurs (with.Java)

   Nov 12, 2023     2 min read

This is a recap of the ā€œCount how many times a string appearsā€ problem.

Weā€™re going to go through the process of solving a coding test problem, reflecting on how we solved it, and exploring other ways to solve it.

Letā€™s start with the problem

Problem

You are given the strings myString and pat.

Complete a solution function that returns the number of times pat occurs in myString.

Example input and output
myStringpatresult
ā€œbananaā€ā€œanaā€2

My solution to the problem

class Solution {
    public int solution(String myString, String pat) {
        int answer = 0;
        for(int i = pat.length() - 1; i < myString.length(); i++){
            String str = myString.substring(0, i + 1);
            if(str.endsWith(pat)){
                answer++;
            }
        }
    } return answer;
}

solution description

public int solution(String myString, String pat): A function that takes two string parameters myString and pat as input and solves the problem. It returns an integer value as result.

int answer = 0;: Initialize the variable answer to store the number of substring.

for(int i = pat.length(); i < myString.length(); i++) { ā€¦ }: Runs a loop for each character of the given string myString. The starting position is the length of pat.

String str = myString.substring(0, i + 1);: Generates a substring up to the current position. Use the substring method to generate a substring from the starting index 0 to the current index i. The starting position is the length of pat.

if(str.endsWith(pat)) { ā€¦ }: Checks if the generated substring str ends with the given string pat.

answer++;: If the substring ends with pat, increment the value of answer by 1.

return answer;: Returns the value of answer, which is the number of substitutions finally found.

The code performs the task of counting the number of substitutions in the given string myString that end in pat. The code is solving the problem correctly, and it uses the endsWith method to check if the end of the string matches the given pattern.