Char Substring

I'm quite new to Arduino programming but am totally hooked :slight_smile: . What I thought would be an easy challenge has proven problematic. I've done lot's of reading, learnt loads about memory allocation, pointers, addresses and null pointers. However I still come up against a brick wall.

In the simplest terms I need to return a substring from a string, not from the String class but from char. Have tried a dozen different inventive ways without success.

Latest attempt was part inspired from https://forum.arduino.cc/index.php?topic=568927.0

char myChar[] = "Hello Mum";


void setup() {
  Serial.begin(9600);
  char returnChar[3];  //Char to store sub string 0-4 i.e. 4 elements
  char * ptrMum = strchr(myChar, "M");  //Pointer to address of "M" in "Hello Mum"
  strncpy(returnChar, ptrMum, 3);  //Copy in to returnChar, from the pointer, copy 3 characters
  returnChar[3] = '\0';  //Put a null pointer at array 3
  Serial.print("This is the result ");
  Serial.println(returnChar);  //Returns This is the result with followed by a square box
}
void loop(){
}

In this example I'm using strchr to get the pointer of capital "M" in myChar.
I then use strncopy to copy 3 elements of that array into returnChar.
However when I output to the serial port I get a reverse question mark or box.

Can someone put me out of my misery by switching the light on?

Thanks in advance.

returnChar[3] = '\0';

That's outside returnChar. You defined it as having 3 elements, that's the 4th one because they start at 0.

"M" -----> 'M'

Opening/closing single quotes (' ') are used to qualify a character.
Openin/closing double quotes (" ") are used to qualify a string (more than one character).

strchr(arg1, arg2) searches for the first occurrence of a character (not a string) indicated by arg2.

smlQ.png

smlQ.png

GolamMostafa you are a star!

Head in hands that it should be something so simple having tried so many things. You have switched the light on for me!

Thanks everyone for helping me out on this. I look forward to the day when I can do the same for someone else.

Howard

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.