0% found this document useful (0 votes)
16 views2 pages

Character Strings

Uploaded by

Altan Blu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views2 pages

Character Strings

Uploaded by

Altan Blu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

1.

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

1.2 Filling up of data


1.2.1 By individual elements
char str1[4];
str1[0] = ‘A’;
str1[1] = ‘B’;
str1[2] = ‘C’;
Serial.println(str1);//ABC

1.2.2 Multiple characters

6.2.2.1 memcpy() – copies a block of memory to another memory location

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

1.3 Formatting strings

6.3.1 use sprint() to easily fill up and format data in a string

sprintf(str3,"hello");
Serial.println(str3);//hello

byte x = 123;

Serial.println(x); // stream class converts x to characters, hence, result


is "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

You might also like