Eliminate spaces, string.replace() and .trim() not possible?

Hello good day Arduino communiy!

I allways got an error while compiling with the String- .trim() or .replace() function.

I`ve also tried some example code:

String stringOne = "<html><head><body>";
Serial.println(stringOne);
String stringTwo = stringOne.replace("<", "</");
Serial.println(stringTwo);

While compiling the sample source (Arduino v1.0) 8. Strings -> StringReplace:

StringReplace.cpp: In function 'void loop()':
StringReplace:22: error: conversion from 'void' to non-scalar type 'String' requested
StringReplace:28: error: conversion from 'void' to non-scalar type 'String' requested
StringReplace:29: error: no match for 'operator=' in 'leetString = leetString.String::replace('e', '3')'
C:\Users...\Documents\Arduino\arduino-1.0\hardware\arduino\cores\arduino/WString.h:83: note: candidates are: String& String::operator=(const String&)
C:\Users...\Documents\Arduino\arduino-1.0\hardware\arduino\cores\arduino/WString.h:84: note: String& String::operator=(const char*)

Thanks in advance
Best regards,

Micha

Read the IDE release notes - http://arduino.cc/en/Main/ReleaseNotes

  • The String class has been reimplemented as well, by Paul Stoffregen. This
    new version is more memory-efficient and robust. Some functions which
    previously returned new string instances (e.g. trim() and toUpperCase())
    have been changed to instead modify strings in place.

It would appear that the example sketches haven't been updated.

This version works:

/*
  String replace()
 
 Examples of how to replace characters or substrings of a string
 
 created 27 July 2010
 by Tom Igoe
 
 http://arduino.cc/en/Tutorial/StringReplace
 
 This example code is in the public domain. 
 */

void setup() {
  Serial.begin(9600);
  Serial.println("\n\nString  replace:");
}

void loop() {
  String stringOne = "<html><head><body>";
  Serial.println(stringOne);
  // replace() changes all instances of one substring with another:
  stringOne.replace("<", "</");
  Serial.println(stringOne);

  // you can also use replace() on single characters:
  String normalString = "bookkeeper";
  Serial.println("normal: " + normalString);
  normalString.replace('o', '0');
  normalString.replace('e', '3');
  Serial.println("l33tspeak: " + normalString);

  // do nothing while true:
  while(true);
}

Just be aware that String class objects waste RAM which isn't exactly plentiful in Arduino.

many thanks for the information!

works fine now :slight_smile:

Hello, mate. :wink:

For trim() you could use it in the same way, just modifying the object, without returning no data.

Then, currently, you can't do this:

String myStringWithSpaceAtTheEnd = "myStringWithSpaceAtTheEnd ";
String myString = myStringWithSpaceAtTheEnd.trim();

But, you can use it in this way:

String myString = "myStringWithSpaceAtTheEnd ";
myString.trim();
1 Like