Character Strings
Character Strings
Character Strings
1.1 Definition
• “strings” are simply character (text) arrays e.g. char buf[21];
• This is different from the String class.
• Usually terminated by a NULL ( aka 0 or ‘\0’ ) to mark the end of the string
syntax: memcpy(destination,source,length);
• Destination – pointer to the destination character string
• Source – pointer to character string where the data is taken from
• Length – number of characters to copy
char str1[4] = "ABC";
char str2[4] = "123";
char str3[21];
memcpy(str3,str1,3);
Serial.println(str3);//ABC
for(byte i=0;i<3;i++)
{
str3[i] = str1[i];
}
str3[3] = 0;
Serial.println(str3);//ABC
memcpy(str3,str2,2);
Serial.println(str3);//12
memcpy(str3,"XYZ",3);
Serial.println(str3);//XYZ
memcpy(&str3[3],"567",3);
Serial.println(str3);//XYZ567
memcpy(str3,&str2[1],2);
Serial.println(str3);//XYZ523
1.2.2.2 memset() – changes each element of the destination string to a specific value up to a certain length
syntax: memset(destination,value,length);
• Destination – pointer to the destination character string
• Value – one byte value you want to place into the destination elements
• Length – number of characters to change
memset(str3,'a',6);
Serial.println(str3);//aaaaaa
memset(&str3[1],' ',4);
Serial.println(str3);//a a
1.2.2.3 for-loop
for(byte i=0;i<6;i++)
{
str3[i] = 'b';
}
str3[6] = 0;
Serial.println(str3);//bbbbbb
sprintf(str3,"hello");
Serial.println(str3);//hello
byte x = 123;
memcpy(str3,"123",3);
Serial.println(str3);//123
sprintf(str3,"VALUE=%d",x);
Serial.println(str3);//VALUE=123
char c = ':'
sprintf(str3,"VALUE%c%d",c,x);
Serial.println(str3);//VALUE:123
sprintf(str3,"VALUE=%5d",x);
Serial.println(str3);//VALUE= 123
sprintf(str3,"VALUE=%05d",x);
Serial.println(str3);//VALUE=00123
int time_hh=1,time_mm=5,time_ss=43;
sprintf(str3,"TIME=%02d:%02d:%02d",time_hh,time_mm,time_ss);
Serial.println(str3);//TIME=01:05:43