String response = "Night_Time";
String Time = "";
int i, flag;
for(i = 0; i < response.length(); i++)
{
if(response[i] == '_')
{
flag = 1;
}
if(flag == 1)
{
Time[i] = response[i];
}
}
The purpose of my code here is to copy the data from String "response" to String "Time" when the condition is met. I do it the same as the way we copy the data in the array. However, it seems like it does not work like that since I print the string "Time" to serial, it returns nothing
When you look at how the operator [] is implemented, you'll see that you get a bogus variable to write into if you try to write behind the length of the array.
so you are never storing anything into Time
What is it you are really trying to achieve ? if response contains '_' then duplicate response into the Time variable?
➜ You can copy one String into another one if you do
Time = response;
You just need to do that when the condition is met.
Here's another way that you could do what I think you want (take some Serial input and transpose pre defined Strings into a Time String). You could make as many as you have chars available.
String responseA = "Night_Time";
String responseB = "Day_Time";
String Time = "";
void setup() {
Serial.begin(115200);
}
void loop() {
if (Serial.available() > 0) {
char inByte = Serial.read();
switch (inByte) {
case '_':
Time = responseA;
break;
case '?':
Time = responseB;
break;
} // end of switch
Serial.println(Time);
} // end of if (Serial.available)
}
Use the SafeString-library.
Strings can eat up all RAM memory over time and then make the code crash
The Name SafeString is program: safe to use
And in your case more comfortable
// https://wokwi.com/projects/396975399677155329
// https://forum.arduino.cc/t/passing-data-from-string-to-another-string/1255815
#include <SafeString.h>
cSF(response, 16); // SafeString that can hold 16 characters
cSF(Time, 16);
void setup() {
Serial.begin(115200);
Serial.println("Setup-Start");
byte i;
byte j;
byte flag = 0; // initialise with ZERO !!
response = "Night_Time";
Time = "";
for (i = 0; i < response.length(); i++) {
Serial.print("response[");
Serial.print(i);
Serial.print("]=#");
Serial.print(response[i]);
Serial.println("#");
if (response[i] == '_') {
Serial.println("found the _");
flag = 1;
j = 0;
}
if (flag == 1) {
if (response[i] != '_') {
Time += response[i];
Serial.print("Time[");
Serial.print(j);
Serial.print("]=#");
Serial.print(Time[j]);
Serial.println("#");
j++;
}
}
Serial.print("Time=#");
Serial.print(Time);
Serial.println("#");
}
}
void loop() {
// put your main code here, to run repeatedly:
}
@pepernamek1 - "time" is a reserved word. "Time" is not a reserved word, but could cause confusion later. @J-M-L shows how to incorporate the word "time" into a safe variable name.