简体   繁体   中英

C/C++ on Arduino string .replace() function is not working

I have this method in Arduino which has its programming language based on C/C++ and it is supposed to replace \\r and \\n so that it prints \\r and \\n as it is, but when I try to run the code it gives an no match for operator error:

void debugmsg(String msgtext) {
  msgtext = msgtext.replace("\r","\\r");
  msgtext = msgtext.replace("\n","\\n");
  Serial.println(msgtext1 + "\r\n");
}

no match for 'operator=' (operand types are 'String' and 'void')

i dont know what's wrong, thank you for helping!

.Replace() is a void function. It modifies the string directly so no need to assign it to anything. Just use it like below and it WILL replace it:

msgtext.replace("\r","\\r");
msgtext.replace("\n","\\n");

The replace() from Arduino is a different function than the one you are using here because here it is C/C++ programming language. That one does return a String

Edit:

As @unwind noticed, the Arduino Documentation states that replace() returns a String. However, the Syntax part AND in their example code HERE , it shows a routine usage of that function which is modifying the string directly and not returning a String ! I don't know. Anyway just use it as my above code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM