Given two strings str1
and str2
as input, I need to determine whether str2
occurs within str1
or not.
Examples:
- Input #1:
occurs("JavaLadders","Java")
- Output #1:
true
- Input #2:
occurs("Problem Panel","Panes")
- Output #2:
false
In my function I took 2 Strings. In for loop I am checking each character position whether that character in str1
matches in str2
. If it does not match I made p=0
and count=0
. If it matches I increment my count
as well as p
.
I also checked whether count
is equal to my str2.length()
. If it is, I move out of the loop and return true
, otherwise I return false
.
public boolean occurs(String str1, String str2)
{
int l1=str1.length();
int l2=str2.length();
int p=0;
int count=0;
int j=0;
for(;j<l1;j++)
{
char ch1=str1.charAt(j);
char ch2=str2.charAt(p);
if(ch1==ch2)
{
p++;
count++;
}
else if(count==l2)
{
break;
}
else
{
p=0;
count=0;
}
}
if(l2==count)
return true;
else
return false;
}
But this test case fails:
- Input:
occurs('Trisect Institute', 'Trisect')
- Output:
null
- Expected output:
true
What am I doing wrong?
str1.contains(str2)
? – dounyy