Go Down

Topic: replace() (Read 657 times) previous topic - next topic

cbrandy

Hi.
I have this project where I use split() and replace().
Now I have a bad feeling that I can't use char* split() and replace() togehter.

code:
Code: [Select]

#include <string.h>

void setup() {
  Serial.begin(19200);
}

void loop(){
char test[] = "s1: 22, s2: 43, s3: 12, s4: 56";
test = test.replace(' ', '');
char *token = strtok(test, ",");
int i = 1;

while(token)
{  // Do something with this word
Serial.print(token);
Serial.println();
token = strtok(NULL, ",");
i +=1;
}
Serial.println();
delay(1000);
}


Cause I get this error message:
split:8: error: request for member 'replace' in 'test', which is of non-class type 'char [31]'

Anny way to solve this?

-Andy

AlphaBeta

You can not call methods on variables of scalar datatypes. You need to look for some c-style function for replacing chars in a c-string.
If you're up for the challenge, you could write your own replace function :)

olikraus

Perhaps, the use of
  char *token = strtok(test, " ,");
and
  token = strtok(NULL, " ,");
(note: " ," instead of ",") might solve your problem
without removing the blanks (if this is intended by replace(' ', '')).

Oliver

robtillaart

Test is an array of char, not a class with member functions, therefor the replace() is not existant => compiler error
From the code I see you want to remove the spaces, you can use an inplace remove like below

Code: [Select]

#include <string.h>

void setup()
{
 Serial.begin(19200);
}

void loop()
{
 char test[] = "s1: 22, s2: 43, s3: 12, s4: 56";
 // test = test.replace(' ', '');
   Serial.println(test);
 remove(test, ' ');
 Serial.println(test);
 
 char *token = strtok(test, ",");
 int i = 1;

 while(token)
 {  // Do something with this word
   Serial.print(token);
   Serial.println();
   token = strtok(NULL, ",");
   i +=1;
 }
 Serial.println();
 delay(1000);
}


void remove(char *str, char r)
{
 char *p, *q;
 p = q = str;
 while (*p != '\0')
 {
   while (*p == r) p++;
   *q++ = *p++;
 }
 *q = '\0';
}

Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

cbrandy

Sweet robtillaart.
Thanks for your help :)
It works!

Now I'm just implent in my own code...

-Andy

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy