String concatenation

Hey,

I’m trying to create a string that’s made of multiple string parts and int variables.
Something like “Alarms: 0; Sales: 0”.

However, I can’t find a normal way of doing it and getting a good result. In the place of the integer variable, there’s a weird char that appear before the number.

Take the following code for example:

String myText = "BEGINNING";

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

void loop() {
    String text = "";
    text.concat("Number 1 - ");
    text.concat(1);
    text.concat("; Number2: ");
    text.concat(2);
    myText = text;
    Serial.println(myText);
    
    delay(500);
}

The output of the above code is:

Number 1 - �1; Number2: �2

I’ve tried using the + operator to combine multiple strings as well, but I get an error that I can’t use a the binary operator + on strings (or char[]…)

1 Like

Here’s my crazy example! Please note, javascript really REALLY spoils you after a while…

String text1 = "ONE";
String text2 = "TWO";
String tempStr = "";
char tempChar[10];
int number1 = 1;
int number2 = 2;

void setup() {
    Serial1.begin(9600);
}

void loop() {
    
    text1 = "The first number is " + text1;
    Serial1.println(text1);
    
    text2 = "The second numbner is " + text2;
    Serial1.println(text2);
    
    text1 = text1 + ". " + text2 + ".";
    Serial1.println(text1);
    delay(2000);
    
    sprintf(tempChar,"%d",number1);
    tempStr = tempChar;
    text1 = "The first number is " + tempStr;
    Serial1.println(text1);

    sprintf(tempChar,"%d",number2);
    tempStr = tempChar;
    text2 = "The second numbner is " + tempStr;
    Serial1.println(text2);

    text1 = text1 + ". " + text2 + ".";
    Serial1.println(text1);
    delay(2000);
    
    text1 = "ONE";
    text2 = "TWO";
}

All of the formatted text could be done in one line if you use a real c string:

int number1 = 1;
int number2 = 2;

char line[32]; /* At least big enough for 31 chars + null. */

sprintf(line, "Number 1 - %d; Number 2 - %d\n", number1, number2);
Serial.print(line);

If your formatted text could be larger, be sure to increase the memory you’ve allocated for line to more than 32 bytes.

1 Like

Thank you @BDub and @mattande.
I decided to choose @mattande’s approach, as it’s smaller and simpler (except for the predefined length of the line), and it’s working smoothly!

I’m still interested in what I did wrong in my original code, if someone has an idea.

Totally forgot about multiple variables in sprintf() while I was completely focused on getting int’s into String objects… there should really be an easier way… C++ has some, but none of them work in the Sparkulator :wink:

Well it has been too old thread but I would like to fix the code that was posted by @dorongutman .

Actually in your code it should be of decimal type instead of string.

text.concat(String(1, DEC));
..
text.concat(String(2, DEC));

Thanks
Narayan