Contents

String within a string (with, Java)

   Apr 20, 2024     1 min read

This is an article that looks into the problem of “strings within strings (with, Java)”.

As I solve coding test problems, I look back on the problems I solved and look into different solution methods to get to know myself.

Let’s look at the problem first.

problem

String str1, str2 are given as parameters.

Complete the solution function so that it returns 1 if str2 is in str1, or 2 if not.

Restrictions

  • 1 ≤ length of str1 ≤ 100
  • 1 ≤ length of str2 ≤ 100
  • The string consists of uppercase letters, lowercase letters, and numbers.

Input/Output Example

str1str2result
“ab6CDE443fgh22iJKlmn1o”“6CD”1
“ppprrogrammers”“pppp”2
“AbcAbcA”“AAA”2

My solution to the problem

class Solution {
     public int solution(String str1, String str2) {
         int answer = 0;
         if(str1.contains(str2)){
             answer = 1;
         }else{
             answer = 2;
         }
         return answer;
     }
}

Solution explanation

public int solution(String str1, String str2): Define a method named solution and receive two strings str1 and str2 as parameters. Returns an integer value.

int answer = 0;: Initialize the variable answer, which will store the result, to 0.

if(str1.contains(str2)): If str1 contains str2, answer = 1;: Assign 1 to answer.

else: Otherwise, answer = 2;: Assign 2 to answer.

return answer;: Finally returns the answer value.