chapter 8 “character arrays and strings” · declaring and initializing string variables: 3 c...
TRANSCRIPT
Chapter 8 “Character Arrays and Strings”
INTRODUCTION
2
A string is a sequence of characters that is treated as a single data item.
String constant: “String constant example.” “ \”String constant example.\”” \” includes double quote in the string.
o printf(“ \”Well Done !\” ”);output: “Well Done !”
DECLARING AND INITIALIZING STRING VARIABLES:
3
C does not support strings as a data type.Strings are represented as character arrays.The general form of declaration of a
string variable is:char string_name[size];
Example: char city[10]; char name[30];
Size = maximum number of characters in the s tr ing p lus one ( for NULL character ‘\0’)
DECLARING AND INITIALIZING STRING VARIABLES:
4
Initialization:Example:
1. char city[18] = “Ahmedabad Gujarat”;2. char city[18] = {‘A’, ’h’, ‘m’, ‘e’, ‘d’, ‘a’, ‘b’,
‘a’, ‘d’, ‘ ’, ‘G’, ‘u’, ‘j’, ‘a’, ‘r’, ‘a’, ‘t’, ‘\0’};3. char string[]={‘G’, ‘o’, ‘o’, ‘d’, ‘\0’};
size is determined from list of values.4. char str[10] = “Good”;
strG o o d \0 \0 \0 \0 \0 \0
DECLARING AND INITIALIZING STRING VARIABLES:
5
Initialization:Example:
1. char str2[3]=“Good”; //compile time error - size is smaller than specified value
2. char str3[5]; str3=“Good”;
we can not separate initialization from declaration.
4. char s1[4]=“abc”;char s2[4];s2=s1; //ErrorArray name can not be used as the left operand of an assignment operator.
TERMINATING NULL CHARACTER
6
The string is a variable-length structure and is stored in a fixed-length array.
The array size is not always the size of string and most often it is much larger than the string stored in it.
Null character end-of-string
READING STRINGS FROM TERMINAL
7
Reading strings from terminal Using scanf function
8
Format specification: %s Example:
char name[11];scanf(“%s”,name);
The problem with the scanf function is that it terminates its input on the first white space it finds.
Reading strings from terminal Using scanf function
9
char name[11];scanf(“%s”,name);
Example: Ajay Patel given as input then scanf takes only Ajay as input because it breaks in blank space (white space).
nameA j a y \0 ? ? ? ? ? ?
Reading strings from terminal Using scanf function
10
Example:char adr1[25], adr2[25];scanf(“%s%s”,adr1,adr2);
Reading strings from terminal Using scanf function
11
Format specification: %ws scanf(“%ws”,name);
Example:char name[10];scanf(“%5s”,name);
The input string RAM will be stored as:
nameR A M \0 ? ? ? ? ? ?0 1 2 3 4 5 6 7 8 9
Reading strings from terminal Using scanf function
12
Format specification: %ws scanf(“%ws”,name);
Example:char name[10];scanf(“%5s”,name);
The input string KRISHNA will be stored as:
nameK R I S H \0 ? ? ? ?0 1 2 3 4 5 6 7 8 9
Reading strings from terminal Using a Line of Text
13
Format specification: %[..] also known as edit set conversion code.
Example,char line[20];scanf(“%[^\n]”,line);
lineA j a y P a t e l \0 ? ? ? ? ? ? ? ? ?
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Reading strings from terminal Using getchar and gets function
14
Using getchar() function char ch; ch=getchar();
Example next slide
Reading strings from terminal Using getchar and gets function
15
#include<stdio.h>void main(){ char line[81],ch; int c=0; printf(“Enter text. Press <Return> at end.\n”); do { ch=getchar(); line[c]=ch; c++; }while(ch!=‘\n’); c=c-1; line[c]=‘\0’;
printf(“line=%s”,line);}
Output:Enter text. Press <Return> at end.String is interesting chapter.line=String is interesting chapter.
Reading strings from terminal Using getchar and gets function
16
Using gets() functionHeader file stdio.hGeneral format
gets(string_variable_name);
g e t s ( ) r e a d c h a r a c t e r s i n t o string_variable_name from keyboard until a new-line character is encountered and then appends a null character to the string.
Reading strings from terminal Using getchar and gets function
17
Example,char line[81];gets(line);printf(“%s”,line);
Reading strings from terminal Using getchar and gets function
18
Difference between gets() and scanf() function
gets() scanf()Format: gets(string_variable_name);
Format: scanf(“%ws”,name);
It can consider white space until new line character encountered.
It can not consider white space while reading a string.
Example, char ch[10]; gets(ch);
Example, char ch[10]; scanf(“%s”,ch);
It is used to read line of text. It is not used to read line of text but word.
Writing strings to screen
19
WRITING STRINGS TO SCREEN USING PRINTF() FUNCTION
20
Format specification: %w.p sHere w – width and p – first p characters
of the string.Examplechar name = “Ajay Patel”;
printf(“%s”,name);
printf(“%10s”,name); A j a y P a t e l
A j a y P a t e l
WRITING STRINGS TO SCREEN USING PRINTF() FUNCTION
21
When the field width is less than size of string, entire string is printed
char name = “Ajay Patel”;printf(“%5s”,name);
The integer on right side of decimal indicates number of characters to be printed
printf(“%15.6s”,name);
printf(“%-15.6s”,name);
A j a y P a t e l
A j a y P
A j a y P
WRITING STRINGS TO SCREEN USING PRINTF() FUNCTION
22
char name = “Ajay Patel”; printf(“%15.0s”,name);
0 characters are to be printed. So nothing is printed on the screen.
printf(“%.3s”,name);
printf(“%*.*s”,w,p,string);printf(“%-*.*s”,15,6,name);
A j a
A j a y P
23
(Contd.)
24
Writing strings to screen using putchar() and puts() function
25
Using putchar() function:char ch=‘A’;putchar(ch);
Example,char name[5]=“Ajay”;i=0;while(name[i]!=‘\0’){ putchar(name[i]); i++;}putchar(‘\n’);
A j a y \0
Writing strings to screen using putchar() and puts() function
26
Using puts() function:Format: puts(string_variable_name)It prints the string on the screen then
move the cursor to the beginning of the next line on the screen.
Example,char name[20];gets(name);puts(name);
ARITHMETIC OPERATIONS ON CHARACTERS
27
Whenever a character constant or character v a r i a b l e i s u s e d i n e x p r e s s i o n , i t i s automatically converted into an integer value by the system. The integer value depends on the local character set of the system.
If the machine ASCII representation,char x=‘a’;printf(“%d\n”,x); output:- 97
Arithmetic operations can be performed on character constant or character variable.
x=‘z’-1; 122(ASCII of z) - 1 = 121
ARITHMETIC OPERATIONS ON CHARACTERS
28
To check whether the character is upper-case letter or not.
ch >= ‘A’ && ch <= ‘Z’
We can convert a character digit to its equivalent integer value using the following relationship.
x = character – ‘0’ // Here x is interger.Example,
x= ASCII value of ‘7’ - ASCII value of ‘0’ = 55 – 48 = 7
29
ARITHMETIC OPERATIONS ON CHARACTERS
30
The C library supports a function that converts a string of digits into their integer values. The function takes the form
integer_variable = atoi(string);Example,
char number[5] = “2013”;int year;year = atoi(number);
atoi() function is stored in the header file stdlib.h .
PUTTING STRINGS TOGETHER
31
We can not join two strings together by the simple arithmetic addition.
Like, string3 = string1 + string2; string2 = string1 + “hello”; are not valid.
The characters from string1 and string2 should be copied into the string3 one after the other.
The size of array string3 should be large enough to hold the total characters.
The process of combining two string together is called concatenation.
COMPARISON OF TWO STRINGS
32
Similarly, C does not permit the comparison of two strings directly.
Like, if(name1==name2)if(name1==“Ajay”) //are invalid
It is therefore necessary to compare the two strings to be tested, character by character.
33
STRING HANDLING FUNCTIONS
34
Most commonly used s tr ing handl ing functions:
Function Action
strcat() Concatenates two strings
strcmp() Compares two strings
strcpy() Copies one string over another
strlen() Finds the length of a string
STRING HANDLING FUNCTIONS STRCAT() FUNCTION
35
It joins two strings together. It takes the following form:
strcat(string1, string2);string2 is appended to string1.
Example refer next slide
STRING HANDLING FUNCTIONS STRCAT() FUNCTION
36
Examplechar name[15] = “Ajay ”;char sname[6] = “Patel”;strcat(name,sname);
nameA j a y \0
sname
P a t e l \0
nameA j a y P a t e l \0
STRING HANDLING FUNCTIONS STRCAT() FUNCTION
37
Examplechar name[15] = “Ajay ”;strcat(name,”Patel”);
nameA j a y \0
nameA j a y P a t e l \0
STRING HANDLING FUNCTIONS STRCAT() FUNCTION
38
Examplechar name[15];char fname[6]=“Ajay ”,lname[6]=“Patel”;strcat(strcat(name,fname),lname);
fnameA j a y \0
nameA j a y P a t e l \0
lname
P a t e l \0
STRING HANDLING FUNCTIONS STRCMP() FUNCTION
39
It compares two strings and has a value 0 if they are equal . If they are not , it has numeric difference between the first non-matching characters in the strings.
It takes the following form:strcmp(string1, string2);
Example refer next slide
STRING HANDLING FUNCTIONS STRCMP() FUNCTION
40
Examplestrcmp(“their”,”there”);It returns a value -9 (Ascii of (i) - Ascii of (r) ).
STRING HANDLING FUNCTIONS STRCMP() FUNCTION
41
Examplechar name1[15]=“Ajay”;char name2[15]=“Ajay”;int x;x = strcmp(name1,name2);if(x != 0){ printf(“strings are not equal. ”); }else{ printf(“strings are equal. ”); }
42
Sorting of strings in alphabetical order
STRING HANDLING FUNCTIONS STRCPY() FUNCTION
44
It copies one string over another. It takes the following form:
strcpy(string1, string2);it assigns the contents of string2 to string1.string2 may be a character array variable or a string constant.
Example,strcpy(city,”AHMEDABAD”);strcpy(city1,city2);
size of the array city1 should be large enough to receive the contents of city2.
STRING HANDLING FUNCTIONS STRLEN() FUNCTION
45
It counts and returns the number of characters in a string.
The general form of strlen is:n = strlen(string);
Where n is an integer variable, which receives the value of the length of the string.
The argument may be a string constant. The counting ends at the first null character.Example
char city[15]=“Ahmedabad”;int n=strlen(city); n=9int x=strlen(“Baroda Gujarat”); x=14
Other String handling functions strncpy() function
46
The header file string.h contains many more string manipulation functions.
It copies only left-most n characters of the source string to the target string variable.
strncpy(s1,s2,5); This statement copies the first 5 characters of
the source string s2 into the target string s1. Since the first 5 characters may not include
the terminating null character, we have to place it explicitly in the 6th position of s2 as shown below:
s1[6]=‘\0’;
Other String handling functions strncpy() function
47
Example,char str1=“Nirma Uni”;char str2=“IDS”; strncpy(str1,str2,2); IDrma Uni
Other String handling functions strncmp() function
48
The general form is:strncmp(s1,s2,n);
this compares the left-most n characters of s1 and s2 and returns 0 if they are equal. Negative number, if s1 sub-string is less than s2 Positive number, otherwise.
Other String handling functions strncat() function
49
The general form is:strncat(s1,s2,n);
This call will concatenate the left-most n characters of s2 to the end of s1.
After strncat(s1,s2,4); excution:
S1: B A L A \0
S2: G U R U S A M Y \0
S1: B A L A G U R U \0
OTHER STRING HANDLING FUNCTIONS STRSTR() FUNCTION
50
It is a two-parameter function that can be used to locate sub-string in a string.
This takes the forms:strstr(s1,s2);strstr(s1,”ABC”);
The function strstr searches the string s1 to see whether the string s2 is contained in s1.
If yes, the function returns the position of the first occurrence of the sub-string.
Otherwise, it returns a NULL pointer.
OTHER STRING HANDLING FUNCTIONS STRSTR() FUNCTION
51
Example,char s1[15]=“Nirma University”, s2[10]=“Uni”;if(strstr(s1,s2)==NULL)
printf(“substring is not found.”);else
printf(“s2 is as substring of s1.”);
OTHER STRING HANDLING FUNCTIONS STRCHR() FUNCTION
52
We also have functions to determine the existence of a character in a string.
The functionstrchr(s1,’m’);
will locate the first occurrence of the character ‘m’.
The function strrchr(s1,’m’);
will locate the last occurrence of the character ‘m’ in the string s1.
TABLE OF STRINGS
53
A list of names can be treated as a table of string and a two-dimensional character array can be used to store the entire list.
Example,char student[30][20];
It is used store 30 student names each of length not more than 20 characters.
Write a C program to copy one string into another without using string handling function.
54
#include<stdio.h>#include<conio.h>void main(){ char str1[50],str2[20]; int i; clrscr(); printf(“Enter the string2:”); gets(str2); for(i=0;str2[i]!=‘\0’;i++) str1[i]=str2[i]; str1[i]=‘\0’; printf(“String1 = %s”,str1); getch();}
Output:Enter the string2:Nirma University
String1 = Nirma University
Write a C program to compare two strings without using string handling function.
55
#include<stdio.h>#include<conio.h>void main(){ char str1[50],str2[20]; int i; clrscr(); printf(“Enter the string1 and string2:”); gets(str1); gets(str2); i=0;
while(str1[i]==str2[i] && str1[i]!=‘\0’ && str2[i]!=‘\0’) i++;
if(str1[i]==‘\0’ && str2[i]==‘\0’) printf(“Strings are equal.”);else printf(“Strings are not equal.”);
getch();}
Write a C program that counts the number of words from the given string
#include<stdio.h>#include<conio.h>void main(){
char str[100];int count=1,i=0;
clrscr();
printf("Enter the string:");gets(str);
while(str[i]!='\0'){ if(str[i]==' ') { count++; } i++;
}printf("\nNo. of words in string are: %d",count);getch();}
56
WRITE A PROGRAM TO PRINT FOLLOWING USING FOR LOOP:
57
58
#include<stdio.h>#include<string.h>void main(){char str[20];int i,j;printf("Enter the string:");scanf("%s",str);for(i=0;i<strlen(str);i++){ for(j=0;j<=i;j++) printf("%c",str[j]); printf("\n");}getch();}
Thank You