Concatenating strings together in Arduino - c++

I want to do something similar to this:
char* a = (char*)msg[0];
char* b = (char*)msg[1];
char* c = a + "," + b;
Where msg is an array of int.
N.B.: This is Arduino C++, not regular C++.

Arduino doesn't use std::string, instead it uses String (note the capital S and dropped std::). They're used the same way as std::string for the most part. So basically you should just be able to do this:
String a("hello");
String b(" world");
c = a + b;
If you want to convert an integer to a String, it has a constructor to do just that, e.g.:
String a = String(msg[0]);
String b = String(msg[1]);
You can find more examples here and here.

See strcat.
You seem to be programming C, not C++.
This should be covered in the most basic tutorials.

SOLUTION
so here is my solution thank everyone.
String a = String(msg[0]);
String b = String(msg[1]);
String c = a + "," + b;
char* d;
c.toCharArray(d,c.length());
mclient.publish("topic1/sensorAck",d);

Related

Converting an int to a string for a to_string method C++

I am writing a lexical analyzer in C++ and have to include a to_string() method for my subclasses. This method won't be used by the lexical analyzer but we are told we have to include them for debugging purposes. The to_string methods I have written keep generating errors and I am not sure why. Here is what I have:
string *AddopToken::to_string()
{
token_type_type tokenType = get_token_type();
addop_attr_type addopAttr = get_attribute();
return "[TOKEN TYPE: " + tokenType + ", ATTRIBUTE TYPE: " + addopAttr + "]";
}
This seems like it should work, but for some reason it does not.
Here is the typedef for addop_attr_type in the AddopToken header.
typedef enum addop_attr { ADDOP_ADD = 400,
ADDOP_SUB = 401,
ADDOP_OR = 402,
ADDOP_NO_ATTR = 499 } addop_attr_type;
So even though the type of addopAttr is addop_attr_type, all that really is is an int constant. I figured C++ could convert an int to a string. Is there a way to convert these variables to a string so my to_string() will work correctly?
C++ doesn't allow + for concatenation of string literals or string literals with integers.
The code you need is
char buff[1204];
sprintf(buff, "[TOKEN_TYPE; %d , ATTRUBUTE_TYPE %d ]", tokenType, addopAttr);
return std::string(buff);
You don't have to use the old C function sprintf, there are also lots of C++ functions people have invented for achieving similar things, and that gets rid of the temporary buffer, but at cost of being harder to follow what is going on underneath.
This should work for you:
Edit: now it returns pointer to a string, Don't forget to delete the pointer after you finish using it.
std::string* AddopToken::to_string() const{
token_type_type tokenType = get_token_type();
addop_attr_type addopAttr = get_attribute();
std::string* result = std::string();
*result = std::string("[TOKEN TYPE: ") + std::to_string(tokenType) + std::string(", ATTRIBUTE TYPE: ") + std::to_string(addopAttr) + std::string("]");
return result;
}
C++ see "[TOKEN TYPE: " as char[14] and not as a string. And to convert int to string use std::to_string().

How can I find text within an wchar_t* array

Sorry for what maybe will be an easy question to answer, but here we go.
itemname2 = tsection.htmlText.Data;
int rf = itemname2.rfind("'>");
itemname2 = itemname2.replace(0, rf + 2, "");
WriteLogFile(itemname2);
The code above works perfectly if I was to be passing a string into itemname2, however
tsection.htmlText.Data = wchar_t *TArray::Data
You can turn itemname2 into a std::wstring and then do it very similar way:
int rf = itemname2.rfind(L"'>");
itemname2 = itemname2.replace(0, rf + (2*sizeof(wchar_t)), "");
You need to use L prefix to let compiler interpret lietral string as a wide one.

Creating an array out of a string

I'm new to C++ and I've encountered a problem... I can't seem to create an array of characters from a string using a for loop. For example, in JavaScript you would write something like this:
var arr = [];
function setString(s) {
for(var i = s.length - 1; i >= 0; i--) {
arr.push(s[i]);
}
return arr.join("");
}
setString("Hello World!"); //Returns !dlroW olleH
I know it's a bit complicated, I do have a little bit of background knowledge on how to do it but the syntax of it is still not too familiar to me.
Is there any way that I could do that in c++ using arrays?
Could I join the array elements into one string as I do in JavaScript?
It would be greately appreciated if you could help. Thanks in advance.
If anyone needs more information just tell me and I'll edit the post.
By the way, my code in c++ is really messy at the moment but I have an idea of what I'm doing... What I've tried is this:
function setString(s) {
string arr[s.size() - 1];
for(int i = s.size() - 1; i >= 0; i--) {
arr[i] = s.at(i); //This is where I get stuck at...
//I don't know if I'm doing something wrong or not.
}
}
It would be nice if someone told me what I'm doing wrong or what I need to put or take out of the code. It's a console application compiled in Code::Blocks
std::string has the c_str() method that returns a C style string, which is just an array of characters.
Example:
std::string myString = "Hello, World!";
const char *characters = myString.c_str();
The closest thing to a direct translation of your function:
string setString(string s) {
string arr;
for(int i = s.length() - 1; i >= 0; i--) {
arr.push_back(s[i]);
}
return arr;
}
A std::string is a dynamic array underneath a fairly thin wrapper. There is no need to copy character by character, as it will do it properly for you:
If the character array is null-terminated (that is, the last element is a '\0'):
const char* c = "Hello, world!"; // '\0' is implicit for string literals
std::string s = c; // this will copy the entire string - no need for your loop
If the character array is not null-terminated:
char c[4] = {'a', 'b', 'c', 'd'}; // creates a character array that will not work with cstdlib string functions (e.g. strlen)
std::string s(c, 4); // copies 4 characters from c into s - again, no need for your loop
If you cannot use std::string (e.g. if you are forced to use ANSI C):
const char* c = "Hello, World!";
// assume c2 is already properly allocated to strlen(c) + 1 and initialized to all zeros
strcpy(c2, c);
In your javascript example, you are reversing the string, which can be done easily enough:
std::string s = "Hello, world!";
std::string s1(s.rbegin(), s.rend());
Additionally, you can cut your iterations in half (for both C++ and Javascript) if you fix your loop (pseudo-code below):
string s = "Hello, world!"
for i = 0 to s.Length / 2
char t = s[i]
s[i] = s[s.Length - 1 - t]
s[s.Length - 1 - i] = t
Which will swap the ends of the string to reverse it. Instead of looping through N items, you loop through a maximum of N / 2 items.

How to access each member of a std::string?

How can I access each member in a std::string variable? For example, if I have
string buff;
suppose buff conatains "10 20 A" as ASCII content. How could I then access 10, 20, and A separately?
Here is an answer for you on SO:
How do I tokenize a string in C++?
There are many ways to skin that cat...
You can access the strings by index. i.e duff[0], duff[1] and duff[2].
I just tried. This works.
string helloWorld[2] = {"HELLO", "WORLD"};
char c = helloWorld[0][0];
cout << c;
It outputs "H"
Well I see you have tagged both C and C++.
If you are using C, strings are an array of characters. You can access each character like you would a normal array:
char a = duff[0];
char b = duff[1];
char c = duff[2];
If you are using C++ and using a character array, see above. If you are using a std::string (this is why C and C++ should be tagged separately), there are many ways you can access each character in the string:
// std::string::iterator if you want the string to be modifiable
for (std::string::const_iterator i = duff.begin(); i != duff.end(); ++i)
{
}
or:
char c = duff.at(i); // where i is the index; the same as duff[i]
and probably more.

Concat string in C++(STL)

i have code like this
string xml_path(conf("CONFIG"));
xml_path+=FILE_NAME;
Where,
conf function returns char * and FILE name is const char *
I want to combine it to one line like
xml_path(conf("CONFIG")).append(FILE_NAME)
how do i do it?
any suggestions ??
Question asked for one line:
string xml_path = string(conf("CONFIG")) + string(FILE_NAME);
(I assume xml_path is the name of the variable, and not some sort of call in a library I don't know about).
Alternatively, if you want to format variable of different type, use a ostringstream.
eg.
std::ostringstream oss;
int a = 2;
char *s = "sometext";
oss<<s<<a<<endl;
cout<<oss.str(); // will output "sometext2"
const char * f = "foo";
char * b = "bar";
string s = string( f ) + b;
Note that you cannot use append(-0 because neither of the strings invvolved is a std:;string. If you really want to append, it will have to be two-stage process:
string s ( f );
s.append( b );
string xml_path(conf("CONFIG"));
xml_path += string(FILE_NAME);
should do the trick.