String.replace replacing "

I tried string.replace(""",""); string.replace(’"’,""); none of them works.

You’re trying to remove them, right? My eyes are getting blurry trying to read that!

void setup() {
    Serial.begin(9600);
    
    String withQuotes = "a \"string\"";
    
    Serial.printlnf("withQuotes=%s", withQuotes.c_str());
    
    String withoutQuotes = withQuotes.replace("\"", "");
    
    Serial.printlnf("withoutQuotes=%s", withoutQuotes.c_str());   
}

output:

withQuotes=a "string"
withoutQuotes=a string
1 Like

@rickkas7
doesn't workI am getting compile error on webIDE

 String str="a \"string\""";
 str.replace( "\"","");

Hi @mtun009

I reformatted your code in the post using the markup:

  ```cpp
  <code goes here>
And it immediately showed me that you have too many closing quotes on the end of the first line.

Try without the back . it won’t compile

String withoutQuotes = withQuotes.replace(""", "");

Hi @mtun009

You know that need the backslash in the first string–check @rickkas7 nice example above for what it should look like. It does work if you write it correctly.

String withoutQuotes = withQuotes.replace("\"", "");
1 Like

yes, but for the argument sake, I just want to remove the quote (") and leave the slash ().

It doesn’t remove the backslashes. The backslash tells the C++ compiler to ignore the end-of-string marker in the following character. Two backslashes in a row in a string means insert a backslash.

void setup() {
    Serial.begin(9600);
    
    String withQuotes = "a \"string with backslash\\\"";
    
    Serial.printlnf("withQuotes=%s", withQuotes.c_str());
    
    String withoutQuotes = withQuotes.replace("\"", "");
    
    Serial.printlnf("withoutQuotes=%s", withoutQuotes.c_str());
    
}

output:

withQuotes=a "string with backslash\"
withoutQuotes=a string with backslash\

Understood but actually I was trying to parse an xml data like this:

to extract value, code, name, etc.

<direction value="20" code="NNE" name="North-northeast"/>

My data string looks like below (intentionally left out <>)

direction value=“20” code=“NNE” name=“North-northeast”/

For the sake of extracting substrings I’d rather use strtok() and not String replacement, since it does a lot of heap messing.
But before that you might want to read up on C strings and escaping special characters in C strings.
This is what @bko and @rickkas7 tried to tell you, but you haven’t quite inhaled yet.

2 Likes

Hi @mtun009

I found this quick reference on C/C++ string escape sequences.

http://en.cppreference.com/w/cpp/language/escape

When the compiler comes to a backlash in string, it interprets the backslash and the next character in a special way so that they equal only one special character in the resulting string. The process is called an escape sequence and backslash is the escape character in C/C++.

1 Like