2
public String getPriceString() {
    String priceString = "45.0";
    String[] priceStringArray = priceString.split(".");
    return priceStringArray.length + "";
}

Why does this give me a 0, zero? Shouldn't this be 2?

1
  • Thanks everyone! I found it out just before refreshing that it's a regex code. Commented Dec 4, 2012 at 13:42

6 Answers 6

6

The argument to split() is a regular expression, and dot has a special meaning in regular expressions (it matches any character).

Try priceString.split("[.]");

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

Comments

2

You need to escape . like that

String[] priceStringArray = priceString.split("\\.");

split takes regular expression as a parameter and . means any character.

http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#sum

Comments

0

escape . with backslash like \\.. . is a regex metacharacter for anything. you will have to escape it with \\. in order to make it treat as a normal character

        String priceString = "45.0";
        String[] priceStringArray = priceString.split("\\.");

Comments

0

String.split takes a regular expression pattern. You're passing in . which means you want to split on any character.

You could use "\\." as the pattern to split on - but personally I'd use Guava instead:

private static final Splitter DOT_SPLITTER = Splitter.on('.');
...

(If you're not already using Guava, you'll find loads of goodies in there.)

Comments

0

You need to escape . as \\. because . has special meaning in regex.

String priceString = "45.0";
String[] priceStringArray = priceString.split("\\.");
return priceStringArray.length + "";

Comments

0

Use String[] priceStringArray = priceString.split("\\."); You will have to use escape sequence.

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.