Skip to content
Advertisement

Split Word into Two and Check Existence in Comma Separated String Sequence

I have a string array for example:

new String[] = {"powerhouse", "p, pow, power, house, pose, poser"};

My goal is to split the first entry in the array in this case powerhouse into any two words and check them against the second entry, which serves as a dictionary of words.

Here’s my implementation so far:

public static String[] convertWordsToArray(String input){
  String[] wordArr = null;
  wordArr = input.split(",");
  return wordArr;
}

public static String splitEm(String[] strArr) {
    String fw = strArr[0];
    String sw = strArr[1];

    String[] arrOne = convertWordsToArray(fw);
    System.out.println(arrOne.length);

    String[] dict = convertWordsToArray(sw);
    System.out.println(dict.length);

    for(int i = 0; i < dict.length - 1; i++) {
         String mWord = fw.split(i, i + 1);
         System.out.println(mWord);
    }

    // Edit Starts Here, tried to substring it but nothing prints in log
      for(int i = 0; i < arrOne.length; i++) {
        String mWord = fw.substring(0, i);
        System.out.println(mWord);
      }

    return ""; // empty for now
}

I am stuck at the part where the first word has to be split. Should I use two loops, one for the first word and the other for the dictionary? I know that somehow the dictionary has to be converted to a list or array list to avail the .contains() method. How do I go about this? Thanks.

Advertisement

Answer

Do you need something like this?

String s = "powerhouse";
List<String> list = new ArrayList<String>();
for(int i = 0; i < s.length(); i++){
    for(int j = i+1; j <= s.length(); j++){
        list.add(s.substring(i,j));
    }
}

System.out.println(list);

I assume you need something like below:

  • Split second string at each , or even better using regex to trim spaces before or after ,
  • check if each part of the splited entry fro above point is made of only the chars contained in the first entry of your input

example

public static void main(String args[]) {
    String[] test1 = {"powerhouse", "p, pow, power, house, pose, poser"};
    String[] test2 = {"powerhouse", "p, xyz, power, house, pose, poser"};
    System.out.println(check(test1));
    System.out.println(check(test2));
}
static boolean check(String[] input){
    String firstEntry = input[0];
    String[] dictionary = input[1].split("\s*,\s*");
    for(int i = 0; i < dictionary.length; i++){
        if(!dictionary[i].matches("["+firstEntry+"]+")){
            return false;
        }
    }
    return true;
}

this will print true for the first case and false for the second as “xyz” is not a valid subpart/substring according to your discription

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement