Sunday 5 April 2015

Using Strings

Strings are nothing more than a array of characters terminated by NULL. The null is not displayed, but it is needed to indicate the end of string to the software.

To hold the NULL character at the end of array the size of string is 1 + no.of characters in string.
ex: to hold "anil" the size of string must be 5. 4 characters and another one to hold NULL character.

string declaration
Actually we do not have to place the null character at the end of character array. the compiler will automatically places it.


String declaration
char string_a[5];//declares string up to 4 characters and NULL and index is like 0,1,2,3,4

char string_b[5] = "anil";//declares string with 4 characters and initializes it

note that in arduino double quotes " " used to indicate string and single quotes ' ' used to indicate characters

char string_c[] = "anil";//compiler initializes the string and calculates its size

char string_d[10] = "anil"; // is same as string_b but has room to grow.

Useful functions to manipulate the Null terminated strings

strlen short for string length
is used to determine the number of characters before the null
ex : int string_a_length = strlen(string_a);

strcat short for string concat
is used to concatenate two strings
ex : strcat(string_a,string_b);//concatenates strings_b on the end of string_a

strcmp short for string compare
is used to compare two strings
ex:strcmp(string_a,string_b);//returns 0 if both are same, lessthan zero if string_a < string_b

strncpy short for string copy
is used to copy string source to destination
ex : strncpy(string_c,string_a);//which copies string_a to string_c

Arduino code to demonstrate strings

char string_a[] = "anil";
char string_b[] = "kunchala";

unsigned int cmp_value;

void setup(){
Serial.begin(9600);
int length_a = strlen(string_a);
int length_b = strlen(string_b);

Serial.print("the length of string_a is \t -->\t");
Serial.print(length_a);
Serial.println("");
Serial.print("the length of string_b is \t -->\t");
Serial.print(length_b);
Serial.println("");
Serial.print("the string come by concating string_a and string_b is \t -->\t");
strcat(string_a,string_b);
Serial.print(string_a);
Serial.println("");
Serial.print("the length of newly formed string is\t --->\t");
int length_c = strlen(string_a);
Serial.print(length_c);
Serial.println("");
}//end of setup

void loop(){
//do nothing here
}//end of loop



and the result isstring_code

No comments:

Post a Comment