In: Computer Science
Write a Java method that takes an array of char and a String as input parameters and and returns an boolean. The method returns true if we can find the input string inside the array by starting at any position of the array and reading either forwards or backwards.
Solution :
Steps for the program :
Following is the Java program for the same :
public class solve {
public static boolean isPresent(char[] charArray, String s)
{ //This string will store reverse of string s
String rev="";
for(int i=s.length()-1;i>=0;i--){
rev+=s.charAt(i);
}
// Check for the condition for forward string and backward string
if (new String(charArray).indexOf(s) == -1 && new String(charArray).indexOf(rev) == -1)
return false; //string is not present
else return true; //string is present
}
public static void main(String args[]) {
//Testing
//Test 1
String s1="Programmer";
char []array1={'c','d','P','r' , 'o' , 'g' , 'r' , 'a' , 'm' , 'm' , 'e' , 'r' , 'e' , 'H' , 'A' , 'S'};
if(isPresent(array1,s1))
System.out.println("Given string is present in the char array!");
else System.out.println("Given string is not present in the char array (forwards and backwards)!");
//Test 2
String s2="Hello World!";
char []array2={'c','d','!','d' , 'l' , 'r' , 'o' , 'W' , ' ' , 'o' , 'l' , 'l' , 'e' , 'H' , 'A' , 'S'};
if(isPresent(array2,s2))
System.out.println("Given string is present in the char array!");
else System.out.println("Given string is not present in the char array (forwards and backwards)!");
//Test 3
String s3="Thank You";
char []array3={'f','u','e','r' , '-' , 'r' , 'h' , 'T' , ' ' , 'o' , 'l' , 'l' , 'e' , 'Y' , 'O' , 'U'};
if(isPresent(array3,s3))
System.out.println("Given string is present in the char array!");
else System.out.println("Given string is not present in the char array (both forwards and backwards)!");
}
}
Code demo :
Output :