0

I have a string and I split the text using space and put them in an array:

String testmessage = "A/c 123456 is credited Rs. 318.95 on  2015-03-20 A/c balance is Rs. 9183.61 from LIFE";
String[] words = testmessage.split(" ");

In the above string between on and 2015-03-20, there two spaces.

I would like to know is it possible to directly check if words[] contains an empty element, something like .contains.

I know we can check using a for loop but is there direct solution?

Let me know!

Thanks!

2 Answers 2

1

There is no contains method for arrays, but you can use Arrays.asList to convert an array to a List, and then use the contains method in Collection.

if (Arrays.asList(words).contains("")) {
    // do something
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can detect whether there's two (or more) consecutive spaces in a string, with:

if (testmessage.contains("  "))
    // yes it does.

Keep in mind that you will also get a blank entry if the string starts or ends with a space so you may want to catch that as well:

if (
    testmessage.contains("  ") ||
    testmessage.startsWith(" ") ||
    testmessage.endsWith(" ")
) {
    // yes it does.
}

However, you can also use a regular expression in String.split() to make your word extraction work even when there are multiple consecutive spaces:

String[] words = testmessage.split(" +");

The regular expression shown above means one or more spaces, and as many as possible (greedy). This will unfortunately may still give an empty element at the start or end of the array but you can get around that by stripping off the leading and trailing spaces beforehand:

String[] words = testmessage.trim().split(" +");

You may also find it more flexible if you use \s rather than a literal space, since that will cover spaces, tabs, formfeeds and so on. If you know you're only wanting to split on spaces, that's not needed, but it's something you may want to keep in mind.

3 Comments

WOW..I didn't we could use regular expression here with +. So + says 1 or more spacing and split equally right? Thanks!
@user5287166, yes. The elements that will end up in the array be be those things that are between each "largest consecutive group of spaces". In other words, "hello<space><space>from<space><space><space><space>pax" will give you ["hello", "from", "pax"].
Perfect. I got it. Thanks!

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.