Replace String Help

This code Fragment keeps failing the compilation.

            String s_value1 ="This is a test 10-percent-";

            String s_value2 = s_value1.replace("-percent-",  "%");

What am i doing wrong?
Please help.

The ‘%’ sign has a special meaning in C. If you simply want to print the sign, you should use ‘%%’ or resort to the ASCII sign like this: print("%c", 37);
Here, the ‘%c’ is a Caracter placeholder(?) for the variable mentioned after the comma, which in this case is the ASCII value for the %-sign.

Give it a try and let us know if it worked out for you.

Thanks Moors7,
Do you have en “String.replace” example that is excepted by the compiler?

            String s_value1 ="This is a test 10-percent-";
            String s_value2 = s_value1.replace("-percent-","q");

and still get a error:
error: conversion from ‘void’ to non-scalar type ‘String’ requested

@prodders, the thing with String.replace() is, that it does not return an altered string but does the replacement in-place.
After the operation s_value1 will have changed.

The function declaration of String::replace() looks like this:

	void replace(char find, char replace);
	void replace(const String& find, const String& replace);
2 Likes

Hi @prodders

The Arduino String class has two replace methods:

  • one that takes a single character to find and a single character to replace it with
  • another one that takes a String to find (not a char array but a String) and a String to replace it with.

Neither of these return a new String–they both work “in place” on the current String you call then on.

Try this:

String s_value1 ="This is a test 10 Q";
s_value1.replace('Q',  '%');  //note single quotes, not double quotes

String s_value3 ="This is a test 10-percent-";
String s_find = "-percent-";
String s_repl = "%";
s_value3.replace(s_find, s_repl);
1 Like

@prodders, in addition to @BKO 's sample, you can still use double quoted const char* literals, as you scetched out in your own post, since there is a String consructor, that will construct Strings out of your parameters to call the second overload of String::replace() (see my previous post)

String(const char *cstr = "");

so this should work

String s_value1 ="This is a test 10-percent-";
s_value1.replace("-percent-",  "%%"); 
1 Like

Thanks @bko & @ScruffR,
It is working now :smiley:

2 Likes

I moved 6 posts to a new topic: Problems with webserver library