0

For this code, all I want to do is split the original string into words by spaces and use regex to return the words that are not y, 4, !, or ?

However, I'm not sure why this isn't working:

    public static void main (String[] args) {
    System.out.println(makeWords("y are you not 4 !?"));
    //should return string "are you not"
}

public static String makeWords (String str) {
    String[] word = str.split(" ");
    //make array of words
    String result = "";
    for (int i = 0; i < word.length; i++) {
        if (word[i].matches("[^y4!?]")) {
            String str = word[i];
            result += str;
        }
    }
    return result;
}

}

1
  • What do you mean by "isn't working"? Commented Jun 25, 2021 at 14:15

1 Answer 1

3

Your regex checks for words that are a single character (and that character must not match 'y', '4', '!', or '?'). None of your words meet that specification, so your result is empty string.

I think you need to change it like this:

public static String makeWords(String str) {
    String[] word = str.split(" ");
    // make array of words
    String result = "";
    for (int i = 0; i < word.length; i++) {
        if (!word[i].matches("[y4!?]+")) {
            String s = word[i];
            result += s + " ";
        }
    }
    return result;
}

This returns words that are one or more characters (+) and not consisting of combinations of y4!?.

System.out.println(makeWords("y are you not 4 !?"));

Produces:

are you not

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.