Substring program, not working
Hi
Write a static method which takes two strings and returns a boolean saying whether the
first string occurs as a substring within the second. For example, if the strings are
“blis” and “antidisestablishment”, the method should return true. See if
you can write two versions of the method, one using iteration, the other using
recursion. Remember when you are asked to write “a method” it is perfectly
acceptable to write extra helper methods which that method calls. In this case, do not
make use of any of the built-in methods provided by Java in class String, apart from
length, substring and charAt.
Code :
import java.util.Scanner;
class Lab3Q2
// Lab3 Question2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a string: ");
String str1 = input.nextLine();
Scanner input1 = new Scanner(System.in);
System.out.println("Enter another string: ");
String str2 = input1.nextLine();
if (q2(str1,str2)) {
System.out.println(str1 + " is , a substring of " + str2);
} else {
System.out.println(str1 + " is not, a substring of " + str2);
}
}
public static boolean q2(String str1, String str2)
{
boolean word = false;
for(int i =0; i < str1.length(); i++) {
for(int j =0; j < str2.length(); i++) {
if (str2.substring(j,str1.length())== str1){
word = true;
} else {
word = false;
}
}
}
return word;
}
}
my program doesnt seem to work, and I dont know why?
Re: Substring program, not working
You can't compare strings using the == operator, you need to use the .equals() method. Also, in your second loop don't start from 0, but start from i, and it should also be j++ instead of i++ in the second loop. Your substring is taking the wrong sub-string. Change it to take a substring from i to j+1. And lastly, you shouldn't return false right away, but that simply means that that starting character location isn't the correct place to be looking. Once you've looked through the entire str1 of starting locations and haven't found a match, then you can return false.
Re: Substring program, not working
I didn't spot the i++/j++ thing. So thanks, in the end I used
str2.substring(j,j+str1.length()).equals(str1)
that worked fine, and just did a couple of return statements
My Program is working. Thanks
Re: Substring program, not working