Unit 3 Strings
Unit 3 Strings
Unit 3 - Strings
Introduction
• The names of various people, cities, companies, addresses, lots of other official and personal
details are sequence of characters either alphabet or alphanumeric mostly and rarely pure
integers.
• In that case, these are treated as array of characters and most of the applications require
support to read, write, copy, search, concatenate etc.
• In C language, array of characters have been treated as a complete entity named as string
and many special library functions have been provided to process these strings.
• A string is an array of characters terminated a special symbol named as null
character(represented as ‘\0’). Hence the null character is also called as string-termination
character. It is used to identify the length of a string.
• All characters, individual digits, all punctuation/special symbols and all operator symbols can
be stored as characters, as each of them has a separate ASCII code.
• A String consists of n characters can be logically shown as illustrated below.
Defining a String
• String is declared in the same manner as an array, except that its data type is
specified as character.
• In both cases, the null character will be automatically get appended in the end.
• Both of these initializations will result into storage as shown below.
• Strings (i.e., character arrays) are handled somewhat differently
• When a string constant is assigned to a character array as a part of the array definition, the
array size specification is usually omitted.
• The proper array size will be assigned automatically.
• This will include a provision for the null character ‘\0’, which is automatically added at the
end of every string
• Consider the following 2 character array definitions. Each includes the initial assignment of
the string constant "RED". However, the first array is defined as a three-element array,
whereas the size of the second array is unspecified.
char color[3] = "RED";
char color[ ] = "RED";
• The results of these initial assignments are not the same because of the null character, ‘\0’,
which is automatically added at the end of the second string.
• Thus, the elements of the first array are
color[0] = 'R'
color[1] = 'E'
color[2] = 'D'
• whereas the elements of the second array are
color[0] = 'R '
color[1] = 'E'
color[2] = 'D'
color[3] = '\0'
• The first form is incorrect, since the null character ‘\0’ is not included in the array.
• The array definition could also have been written as
char color[4] = "RED"
Reading and Writing a String
• A string can be read and written using a single scanf and printf functions using %s and no
loop is needed, which is compulsory for reading and writing of arrays of other data types.
#include<stdio.h>
int main() {
char str[100];
printf(“\n Enter a string of maximum 100 characters : “);
scanf(“ %s “,str);
printf(“\n The entered string is : %s”, str);
return 0;
}
• When the program is executed its output will look like:
• Input / Output 1:
Enter a string of maximum 99 characters : Programming
The entered string is : Programming
• Input / Output 2:
Enter a string of maximum 99 characters : New Delhi
The entered string is : New
• The scanf() function reads a string from the key board till a whitespace character(blank or tab
or newline) is encountered.
• After the reading is complete, the null character is appended automatically at the next
position inside the array. In first case null character is appended at str[11]. During printing,
the printf function keeps on printing the individual characters of the array till the null
character is not reached.
• The scanf function with %s is used to read strings not consisting of spaces. So, if we give the
input as New Delhi, only New gets stored in the array. So the null character is appended at
str[3].
• To read string consisting of blank characters as well, the gets() functions is the easiest way. To
use gets() and puts() functions, string.h header file must be included.
• Following program is an example to read and print string with spaces.
#include<stdio.h>
#include<string.h>
int main() {
char str[100];
printf(“\n Enter a string of maximum 100 characters : “);
gets(str);
puts(“\n The entered string is :”);
puts(str);
return 0;
}
• Another alternate to read a string consisting of alphabets, digits, blanks, punctuation symbols
is,
scanf(“%[^\n]”, str);
Which reads all characters till the enter key (that is ‘\n’) is not pressed.
#include<stdio.h>
int main() {
char str[100];
printf(“\n Enter a string of maximum 100 characters : “);
scanf(“%[^\n]”,str);
printf(“\n The entered string is : %s”, str);
return 0;
}
• Strings can be read or written character by character also. This method is similar to reading
the elements of an array of integers, with a difference that the end of the input is detected
by pressing the “Enter key”.
• This method requires the use of scanf with %c or getchar functions.
• Example: Using scanf function:
#include<stdio.h>
int main() {
char str[100];
int i = 0;
do {
scanf(“%c”, &str[i]);
i = i + 1;
}while(str[i -1] != ‘\n’);
str [i]= ‘\0’;
printf(“\n The entered string is : %c”, str);
return 0;
}
• Example: Using getchar function:
#include<stdio.h>
int main() {
char str[100];
int i = 0;
do {
str[i] = getchar();
i = i + 1;
}while(str[i -1] != ‘\n’);
str [i]= ‘\0’;
printf(“\n The entered string is : %s”, str);
return 0;
}
• Example: Displaying string character by character using printf
#include<stdio.h>
int main() {
char str[100] = “Welcome to SASTRA”;
int i = 0;
while(str[i ] != ‘\0’) {
printf(“%c”, str[i]);
i = i + 1;
}
return 0;
}
• Example: Displaying string character by character using putchar functions
#include<stdio.h>
int main() {
char str[100] = “Welcome to SASTRA”;
int i = 0;
while(str[i ] != ‘\0’) {
putchar(str[i]);
i = i + 1;
}
return 0;
}
Processing Strings
• The strings can be processed either by using some predefined functions with the help of the
string.h header file or by processing all characters individually.
• Many useful predefined functions provided in string.h header file.
• Some commonly used predefined functions are,
stringcopy(str2, str1);
char ch = ‘A’;
printf(“\n %c”,ch); // This statement will print A
ch ++; // This statement will increment the ASCII code of ‘A’
printf(“\n %c”, ch); // This statement will print B
• Some more examples:
#include<stdio.h>
#include<string.h>
int main(){
char text[100];
int i;
printf("\n Enter a line of text : ");
scanf("%[^\n]",text);
len = strlen(text);
for(i=0;i<len;i++){
if(text[ i ] >=‘a’ && text[ i ] <=‘z’)
text[ i ] = text[ i ] + (‘A’ – ‘a’);
}
printf(“\n Upper case of given input string is : %s”, text);
}
Searching and Sorting of strings
• Sorting→ arrange the name in alphabetical order
• Searching→ pattern of characters occurs in a given
text
• Searching of substring requires finding all of the
characters of the substring are present from anu
position onwards in the main string
• Searching start from subscript ‘0’ of the main string
and checking whether all characters of the substring
are present in the same sequence from 0th position
onwards or not.
Keyword searching in a text
#include<stdio.h>
#include<string.h>
main() Output:
{ String: The programming is a systematic
char text[100], substr[30];
process.
int text_len, sub_len, i, j;
printf("Enter the main string"); Substring: pro
gets(text); Subscript: 4
printf("Enter the substring to be searched"); 32
gets(substr);
text_len = strlen(str);
sub_len = strlen(substr);
for(i=0; i<text_len-sub_len; i++)
{
for(j=0; j<sub_len; j++)
if(text[i+j]==substr[j])
continue;
else
break;
if (j==sub_len)
printf("the substring is present from %d,"i);
}
}
Sorting an array
• Store the string within a 2D character array
• Each string will be stored in a separate row within the array
• strcmp → compare two strings (accept two strings as an
argument and returns an integer value)
• Negative value→ first string precedes the second string
alphabetically
• Zero→ both are identical
• Positive value→ second string precedes the first string
• Strcpy→ copy one string to another
• Strcmpi→ compare both upper and lower letters
Sorting a set of city names in an alphabetical order
#include<stdio.h>
for(i=0; i<n; i++)
#include<string.h> {
main() for(j=i+1; j<n; j++)
{ if(strcmp(str[i], str[j])>0)
{ strcpy(s,str[i]);
char str[100][100], s[100]; strcpy(str[i],str[j]);
int i, j, n; strcpy(str[j], s);
printf("Enter number of city names:"); }}}
printf(“The sorted city names are:");
scanf(“%d”,&n); for(i=0; i<n; i++)
printf("Enter city names in any order:"); { printf(“%s”, str[i]);}}
for(i=0; i<n; i++)
{scanf(“%s”,&str[i]);
}
Other string functions
• strcpy(dest, src, n) → copy upto n char from src to dest
• strncmp(str1, str2, n)→ compare n char in str1&str2
• strncmpi(str1, str2)→ ignore case sensitive
• strlwr(str1)
• strupr(str1)
• strncat(dest, src, n)
• memcpy(dest, src, n)→ copy first n bytes of strings str1 and str2
• memcmp(dest, src, n)
• memset(str1, ch, n)
• strchr(str1, ch)
• strset(str1, ch)
• strnset(str1, ch, n)
• strrev(str1)
• strstr(str1,str2)
• i to a(val,str1,radix)
• a to i(str1)