In: Computer Science
This is a java coding String manipulation Question.
Let us say I have a String which looks something likes this:
String x = "MATH,PHYSICS,CHEMISTRY,CODING"
And then I have another String which looks something like this:
String y = "XXXXMXXXAXXXTXXXXHXXXXXXCXXXXOXXXXDXXXIXXXXNXXXGXXXX"
and another String that looks like this:
String z = "XXXXHXXTXXXXAXXMXXXXXCXXXOXXXDXXXIXXXNXXXG"
I want to take String y and print the words that are found in String x as such:
Math
Coding
and for String z if I want to take it and print the words also found in x as such:
Math
Coding
So basically I want to the program to print the possible words from the letters I have in String y and z.
and only print possible words from my String x.
I want to know how I can do such thing please explain so that I understand what is going on. I have tried replacing the Xs with nothing and then I would have the letters and then I'll use it to check if it has something in String x. but that made me use arrays and also if I replaced Xs with nothing and I had to words in Z or Y then I'll end up with something I can not work with only letters.
I have also thought about making a char array from the resulting String after replacing Xs. and then split String x by ',' and after make a char array of each word and then check if the char array of each word contains the chars of the resulting String after replacing Xs with nothing.
but that also does not work.
I think this is a simple problem that I am over complicating.
Please help and thank you.
/******************************************************************************
Online Java Compiler.
Code, Compile, Run and Debug java program online.
Write your code in this editor and press "Run" button to execute
it.
*******************************************************************************/
public class Main
{
public static void main(String[] args) {
String x =
"MATH,PHYSICS,CHEMISTRY,CODING";
String y =
"XXXXMXXXAXXXTXXXXHXXXXXXCXXXXOXXXXDXXXIXXXXNXXXGXXXX";
String z =
"XXXXHXXTXXXXAXXMXXXXXCXXXOXXXDXXXIXXXNXXXG";
String wordsInX[] =
x.split(",");
System.out.println("In String y the
words that are found in String x as such:");
printWords(wordsInX,y);
System.out.println("\nIn String z
the words that are found in String x as such:");
printWords(wordsInX,z);
}
public static void printWords(String array[],String
inputString)
{
//traversing to each word to check weather that word
is present in that string or not
for(String word:array)
{
boolean flag = false;
//in that word checking each
character is present in that input string or not
for(int
i=0;i<word.length();i++)
{
if(inputString.contains(word.charAt(i)+""))
{
flag = true;
}
else
{
flag = false;
break;
}
}
//if each character in that word is
present in input string printing that word to console
if(flag)
{
System.out.println(word);
}
}
}
}