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]');

3 Answers 3

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

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

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

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
If you already have a string, there's no need to convert it. Just substring the string you have.
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);

3 Comments

You aren't checking bounds. What if n > m?
Also, std::string has a constructor for that.
@IvanRubinson : As OP has mentioned that, he/she would like to convert first 4 or 5 character to string. Hence i assumed that, m > n.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.