4

Every time I write " my compiler assumes I am trying to write a String. Instead I want my method to tell me if the incoming string starts with a double quote "" Ex:

String n;
if(n==n.startsWith(" " " ));

doesn't work

Any suggestions??

3
  • Define : doesn't work. Commented Feb 1, 2015 at 17:07
  • have you tried '"' or "\"" instead of " " " in your startsWith approach? the actual regex to match double quotes at the beginning of a string is ^", but each language has different notation for regex literals, most common would be /^"/ I guess Commented Feb 1, 2015 at 17:09
  • 2
    Which language? Escape the double quotes with a backslash String n; if(n==n.startsWith(" \" " )); Commented Feb 1, 2015 at 17:10

1 Answer 1

9

You have to escape double quotes in string! If you do it like this: " " ", string ends on second quotation mark. If in Java, you code should be like:

String n;
if(n.startsWith("\""))
{
    // execute if true
}

Since you are matching just first character, you don't need to use such sophisticated tool as regular expressions:

String n;
if (n.charAt(0)=="\"")
{
    // execute if true
}

BUT. You should make sure if string is not empty. Just for safety:

String n;
    if (n.getText()!=null 
        && !n.getText().isEmpty() 
        && n.charAt(0)=="\"")
    {
        // execute if true
    }

PS: space is a character.

PSS: flagged as dublicate.

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

2 Comments

Java says == doesn't work for string and char
It doesn't work for string.. and any complex object. It can also cause problems with float type. Should be fine with char. I think ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.