0

I am using Arduino and receiving a string from serial. I have converted that string into a character array. But I need to convert first 4 or 5 elements of that array back to string. Is there any way to do that?

I tried the following but it doesn't work:

String str= String('a[0]');
Garf365
  • 3,619
  • 5
  • 29
  • 41

3 Answers3

2
char* data = ...;
int size = 4;
std::string str(data, size);

It's elegant with constructor of std::string.

0

What you want is the substr method of std::string.

You can convetr the char[] to an std::string, and then use substr to get the sub-string you want.

std::string str("The quick brown fox jumps over the lazy dog");
std::cout << str.substr(0, 9);

Output would be:

The quick

Community
  • 1
  • 1
Ivan Rubinson
  • 3,001
  • 4
  • 19
  • 48
  • thank you for your quick response ivan. what im trying to do here is to get a string from serial. if the string starts with COMSTEP, go into the function in which i analyze the rest of the string and tokenize it. string comprise of characters seperated by spaces. do i have to convert the string to char or is there any other way to do that? P.S: im a noob at arduino. so any help is appreciated – Ismail Khawaja Aug 16 '16 at 12:04
  • If you already have a string, there's no need to convert it. Just substring the string you have. – Ivan Rubinson Aug 16 '16 at 12:06
0
char arr[m];
std::string str="";
for(int i = 0; i < n; i++) {
    str += arr[i];
}

I have assumed that you would like to convert first n element of char aar into string.

Or

char* inp = ..;
int size = 4; // int size = 5;
std::string str(inp, size);
Shravan40
  • 8,922
  • 6
  • 28
  • 48