I want to concatenate multiple String of same array
For example
String num[20];
String con;
num[1]="ghjjvfvj";
num[2]="478gbnn";
Con=num1+num2;
How can I do that correctly;
Did you mean
con = num[1] + num [2];
Please remember to use code tags when posting code
Yes
And ..?
(What's wrong with num [0] ?)
I just gave example no matter num[0] num [20]
Just an example
And... what's the problem?
(Note: there is no num [20]
)
What's the difference between
Con=String num[1]+ String num[2];
Con=num[1]+ num[2];
I'm going to be that annyoing guy, but I would strongly recommend using char[] instead of String for a variable type when using strings. So you could just do this instead:
#define maxLength 10
char num[20][maxLength]; //20 strings, max of 10 chars including '\0'
snprintf(num[0], maxLength, "ghjjvfvj");
snprintf(num[1], maxLength, "478gbnn");
char concatenatedString[2*maxLength];
snprintf(concatenatedString, 2*maxLength, "%s%s", num[0], num[1]);
or, if you would like to make a function to deal with this for you, you could use:
void myConcatenate(const char *str1, const char *str2, char *result, size_t resultSize)
{
snprintf(result, resultSize, "%s%s", str1, str2);
}
which you could then call using:
char myNewString[20];
myConcatenate("hello ", "world", myNewString, sizeof(myNewString));
Serial.print(myNewString);
You will get a lot of discussion about the 'correct' way to do that but this code just works
String num[20];
String con;
num[1]="ghjjvfvj";
num[2]="478gbnn";
Serial.println(num[1]);
Serial.println(num[2]);
con=num[1]+num[2];
Serial.println(con);
Output
ghjjvfvj
478gbnn
ghjjvfvj478gbnn
As much as I think Strings are useful, what you are doing does not seem usual. In what context (what larger sketch) do you need to do that concatenation.
This code may be better for your purpose if the 'String [ ]' is constant.
char num[][9] = {"","ghjjvfvj","478gbnn"}; // 3 char *, num[0] num[1] num[2]
Serial.println(num[1]);
Serial.println(num[2]);
String con = num[1];
con += num[2];
Serial.println(con);
Be sure to turn all the compiler warnings on and look out for
warning: initializer-string for array of chars is too long
if the [9] is not large enough for the longest string AND its terminating '\0'
The compile will still work (being C/C++ it assumes you know what you are doing) but you will get odd results due to missing '\0' in some of the strings.
And if you are going to use Strings a lot check out my Taming Arduino Strings tutorial
This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.