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??

Jens
  • 67,715
  • 15
  • 98
  • 113
user4557512
  • 49
  • 1
  • 1
  • 5
  • Define : doesn't work. – Alexandre Lavoie Feb 01 '15 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 – Aprillion Feb 01 '15 at 17:09
  • 2
    Which language? Escape the double quotes with a backslash String n; if(n==n.startsWith(" \" " )); – Jens Feb 01 '15 at 17:10

1 Answers1

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.

Tymek
  • 3,000
  • 1
  • 25
  • 46