I write this code but I don't know why doesn't work.
static boolean findeText(String text1, String text2) {
char c1[] = text1.toCharArray();
char c2[] = text2.toCharArray();
boolean b = false;
for (int i = 0; i <= c1.length - c2.length; i ) {
for (int j = 0, h = i; j <= c2.length; j , h ) {
if (i == c2.length) {
return true;
}
if (c1[h] != c2[j]) {
b = false;
break;
}
}
}
return b;
}
I want find text 2 in text 1 and after that return true or false.
CodePudding user response:
if you want to check if some string contains any other string, just use contains()
method.
In your case that would be
return text1.contains(text2);
Plus you should always write your code in defensive way. That means you should always make sure there will be no NullPointerException
etc. So in your particular case if someone pass either null text1 or null text2, your program will crash.
CodePudding user response:
Above you had NPE in line
if (c1[h] != c2[j])
I have modified your code slightly to get output as requirement.
static boolean findeText(String text1, String text2) {
if ((text1== null) ||(text2==null) || (text1.isEmpty()) || (text2.isEmpty())) {
System.out.println("Invalid input");
return false;
}
char c1[] = text1.toCharArray();
char c2[] = text2.toCharArray();
for (int i = 0; i <= c1.length - c2.length; i ) {
int count = 0;
for (int j = 0; j < c2.length; j ) {
if (c1[i j] == c2[j]) {
count = count 1;
}
if (count == c2.length) {
return true;
}
}
}
return false;
}