7
Handling of Character Strings Topics Declaring String variables Reading String from terminal Writing String to Screen String handling Function

Chap 8(strings)

Embed Size (px)

Citation preview

Page 1: Chap 8(strings)

Handling of Character StringsTopics Declaring String variables Reading String from terminal Writing String to Screen String handling Function

Page 2: Chap 8(strings)

Declaring String Variables A string variable is any valid C variable

name and is always declared as an array. The general form of declaration: char string_name[size];

Ex: char name[20]; When the compiler assigns a character

string to a character array, it automatically supplies a null character (‘\0’) at the end of the string. Therefore, the size should be equal to the maximum number of characters in the string plus one.

Page 3: Chap 8(strings)

Reading and Writing Strings Input function scanf can be used with %s

format specification to read in a string of characters. Ex:

char name[20];

scanf(“%s”,name); The printf function with %s format to print

strings to the screen. Ex:

printf(“%s”,name);

can be used to display the entire contents of the array name.

Page 4: Chap 8(strings)

String Handling functions strcat() Function: The strcat function joins

two strings together. It takes the following form:

strcat(str1, str2); Here str1 and str2 are characters arrays. When

the function is executed, str2 is appended to str1 If str1 and str2 contain “CSE” and “Discipline”

respectively then strcat(str1,str2) produce “CSEDiscipline” to str1.

Page 5: Chap 8(strings)

Continue… strcmp() Function: The strcmp function

compares two strings identified by the arguments and has a value 0 if they are equal. It takes the following form:

strcmp(str1, str2); Str1 and str2 may be string variables or string

constants. Ex: strcmp(name1,name2);

strcmp(name1, “Karim”);strcmp(“Jon”,”Joy”);

If they are not equal then the different of ASCII code of the different character is returned.

Page 6: Chap 8(strings)

Continue… strcpy() Function: The strcpy function works

almost like a string-assigned operator. It takes the following form:

strcpy(str1, str2); Here the contents of str2 is assigned to str1. str2

may be a character array variable or a string constant.

Ex: strcpy(name,”Jon”);

strcpy(name1,name2);

Page 7: Chap 8(strings)

Continue… strlen() Function: The strlen function counts

and returns the number of characters in a string. It takes the following form:

n = strlen(string); Here n is an integer variable which receives the

value of the length of the string. Ex: n=strlen(“CSE”); returns 3 to variable n.