Question

I have searched through-fully all the sides of Stackoverflow and Google, and found nothing to help my problem.

Why is it that this code:

if((w.startsWith("\\$", 0) || (w.startsWith("\\$", 1))){
}

and this:

if((w.charAt(0) == '$') || (w.charAt(1) == '$' && w.charAt(0) == ' ')){
}

and this:

 if((w.startsWith("\\$") || (w.startsWith(" \\$"))){
 }

Does not work?

I'm trying to test if a string starts with a dollar sign, or a space and a dollar sign, but for some ODD reason, I can't seem to find the problem related to the "starts with space" part.

Because the charAt(0) == '$' works just fine... but if I want to test if it starts with a space, then followed by a dollar sign, it doesn't work.

There are no errors... just nothing happens. Any guidelines/fixes would be extremely appreciated!

Was it helpful?

Solution

There is no need to escape the $ as String.startsWith takes just a normal string as argument, not a regex.

if (w.startsWith("$") || w.startsWith(" $"))

will suffice.

If you use String.startsWith(String prefix, int offset) (not required in this case I think) give 0 as offset, not 1 as you have to check from the beginning for a $. It is required if you have to test whether a substring starts with the prefix. In that case, give the beginIndex of substring.

OTHER TIPS

Just do the two startsWith expressions without escaping:

if (w.startsWith("$") || w.startsWith(" $")) {...}

Just trim it. It removes whitespace before and after.

if(w.trim().charAt(0) == '$') {
  ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top