I implemented a substring-method by myself but I'm encountering strange behaviour.
Here is my substring-method:
char *substring(char const *string, int startIndex, int stopIndex){
if(stopIndex>=strlen(string)){
stopIndex = strlen(string)-1;
}
char substring[stopIndex-startIndex+2];
int index = 0;
while(startIndex+index <= stopIndex){
substring[index] = string[startIndex+index];
index++;
}
substring[index] = 0;
return substring;
}
char *substring(char const *string, int startIndex){
return substring(string, startIndex, strlen(string)-1);
}
When using it inside my other code it returns the right substring (I checked it inserting Serial.println(substring) before the "return substring;" in my substring-method) but I can't Serial.println() it outside the substring-method.
Here a code snippet with generated Output:
char *command = inputLine; // inputLine is a charArray[64] which contains "TEMP" with the terminating NULL
command = substring(command, 1);
Serial.println(strlen(command)); // output is: 3
Serial.println(command); // output is a special c but not the expected "EMP". WHY?
If you want to modify the string you're passing as the source, so it just contains the target, there's nothing to stop you writing to the same string you're reading from - as long as you are always writing to a different portion to that which you are reading from.
void substring(char const *string, int startIndex, int stopIndex, char *target){
if(stopIndex>=strlen(string)){
stopIndex = strlen(string)-1;
}
int index = 0;
while(startIndex+index <= stopIndex){
target[index] = string[startIndex+index];
index++;
}
target[index] = 0;
}
char *command = "This is my command, right here.";
substring(command,11,17,command);
"command" would end up with just the word "command" in it.