9 Strings
9 Strings
What is String
• A sequence of characters is often referred to as a character
“string”.
• A string is stored in an array of type char ending with the null
character '\0 '.
• A string containing a single character takes up 2 bytes of storage
Character vs. String
• A string constant is a sequence of characters enclosed in
double quotes.
• For example, the character string:
char s1[2]="a"; //Takes two bytes of storage.
s1:
a \0
• On the other hand, the character, in single quotes:
char s2= `a`; //Takes only one byte of storage.
s2:
a
String Declaration
Format :
char stringname [size];
Example:
char s[10];
String Initialization
Complile time initialization
char s[10]=“SIKKIM”; OR char s[10]={‘S’, ’I’, ’K’, ’K’, ‘I’ ’M’, ’\0’};
S I K K I M \0
Length of the String : No of characters in the array (less the Null Character).
Run time initialization
char s[10];
scanf(“%s”, s); → reading terminates whenever
blank space is encountered
Use header file “string.h”
gets (s); → seamless reading
Display of string
printf(“%s”, s); → print all contents in string s
char s[6]; 0 ‘T’
int i; 1 ‘H’
2 ‘E’
for (i=0; i<6; i++)
3 ‘‘
{ 4 ‘F’
scanf(“%c”, &s[i]); 5 ‘\0’
}
Problem with this approach: The entire array needs to be populated
Approach:
main()
{ • Use loop to read characters
char a[100]; and fill in the array
printf(“Enter String”);
• Terminate reading when some
gets(a); character (say asterisk *) is
printf(“%s”, a); encountered.
} • Replace * with \0
Input: S M I T I N D \0
Output: SMIT IND
Implementation of gets()
main() I Ch ARRAY Test
{ Condi
char a[100], ch; tion
int i=0; 0 N N N0
printf(“Enter text data and press ‘*’ at end);
1 E NE NO
// Reading
2 W NEW NO
do
{ 3 space NEW b NO
ch=getchar(); 4 S NEW S NO
a[i] = ch;
5 K NEW SK NO
i++;
6 Y NEW SKY NO
} while (ch != ‘*’);
i=i-1; 7 * NEW SKY* YES
a[i]=‘\0’; 8 -- --- ---
// Display the string
‘i’ will change to 7
printf (“%s”, a);
‘\0’ will override *
}
N E W S K Y \0
Count the characters in the string
strlen (name_of_string); Strlen() returns Integer Value
printf("Length of the string: %d", i); printf("Length of the string: %d", i);
return 0; return 0;
} }
Output: 4
Copying of Strings
Str1 S M I T \0
Copy the content
Str2 S M I T \0
Built-in Function
strcat (destString, SrcString); Without Built-in Function
for(i=0; s1[i]!='\0'; i++)
main() { {
char s1[10], s2[100]; }
gets(s1);
gets(s2); for(j=0; s2[j]!='\0'; j++)
strcat(s2,s1); {
} s1[i+j]=s2[j];
S1 A B \0 }
s1[i+j]='\0';
S2 P Q A B \0
Combining strings contd..
S1 S2
S M I T \0 I N D I A \0
S3
S M I T I N D I A \0
When i 4
for(i=0; s[i] != ‘\0’; i++) Condition – Violated
{ Copying from S1 to S3 does not take
s3[i]=s1[i]; place
} S[4] ‘ ‘
s3[i]= ‘ ‘ ;
for(j=0;s2[j]!=‘\0’;j++) Now i stands at 4
{
s3[i+j+1]=s2[j]; When j 0
Copying from S2 to S3 takes place
}
from position 5 at s3
s3[i+j+1]=‘\0’; This continues.
Comparing Strings
• Built in function
• strcmp(string1, string2);
Program exercise: