Strings
Strings
Strings
• Introduction
• Declaring and Storing strings
• Initializing strings
• Accessing elements of the strings
• Operations on strings
• Array of strings
Introduction
• Computers are widely used for word processing applications such as creating, updating, inserting and
modifying the textual data – We need to search for a particular pattern within a text, delete it or replace it
with another pattern.
• In C, String is a null-terminated character array.
• After the last character, a null character ('\0') is stored to signify the end of the character array. For example, if
we write char str[] = "HELLO";
• Here, we are declaring an array that has five characters, namely, H, E, L, L, and O. Apart from these
characters, a null character ('\0') is stored at the end of the string. So, the internal representation of the string
becomes HELLO'\0’.
• To store a string of length 5, we need 5 + 1 locations (1 extra for the null character). The name of the
character array (or the string) is a pointer to the beginning of the string.
• If we had declared str as char str[5] = "HELLO"; then the null character will not be appended
automatically to the character array. This is because str can hold only 5 characters and the characters in
HELLO have already filled the space allocated to it.
Difference between character storage and
string storage
Accessing the elements of a string
• We use subscripts to access the elements of a string.
• The subscript starts with a zero (0). All the characters of a string are stored in successive memory locations
3. Strings can also be read by calling the getchar() function repeatedly to read a sequence of
single characters (unless a terminating character is entered) and simultaneously storing it in a
character array
Reading strings contd..
3. Using getchar(),getch()or getche() function repeatedly.
i=0;()
ch = getchar;// Get a character
while(ch != '*’)
{
str[i] = ch;// Store the read character in str
i++;
ch = getchar();// Get another character
}
• In this method, you have to deliberately append the string with a null character.
Reading strings using getchar() repeatedly
#include <stdio.h>
int main()
{
int i = 0;
char ch;
char str[10];
printf("Enter a character \n");
ch = getchar();
while(ch!='*')
{
ch = getchar();
str[i] = ch;
i++;
}
str[i] = '\0’;
printf(str);
return 0;
}
Writing strings
•Strings can be displayed on the screen using the following three ways:
•Using printf() function,
•Using puts() function, and
•Using putchar() function repeatedly.
•Using printf() function printf("%s", str);
•Use format specifier %s to output a string.
•‘&’ character is not used with the string variable.
•Width and precision specifications can also be used along with %s.
•The width specifies the minimum output field width. If the string is short, the extra space is either left padded or right padded.
A negative width left pads short string rather than the default right justification.
•The precision specifies the maximum number of characters to be displayed, after which the string is truncated.
•For example, printf ("%5.3s", str);
•The above statement would print only the first three characters in a total field of five characters. Also these characters would
be right justified in the allocated width.
•To make the string left justified, we must use a minus sign. For example,
•printf ("%–5.3s", str);
•When the field width is less than the length of the string, the entire string will be printed. If the number of characters
to be printed is specified as zero, then nothing is printed on the screen.
Writing strings
• puts(str);
• puts() is a simple function that overcomes the drawbacks of the printf() function.
• Using putchar() function Strings can also be written by calling the putchar() function repeatedly to print a sequence of single
characters.
i=0;
while(str[i] != '\0')
i++;
}
Operations on strings
• Finding the length of a string
• Converting characters of a string into Uppercase / Lowercase
• Appending a string to another string
• Comparing two strings
• Reversing a string
• Extracting a substring from a string
• Inserting a string in the main string
• Pattern matching
• Deleting a substring from the main string
• Replacing a pattern with another pattern in the main string
Finding the length of a string
• The number of characters in a string constitutes the length of the string.
• Blank spaces are also counted as characters in the string
• Write a program to find the length of a string.
#include <stdio.h>
int main()
{
char str[100];
int i = 0, length;
printf("\n Enter the string : ");
fgets(str, 100, stdin);
while(str[i] != '\0’) stdin To read from
i++; the standard input
length = i;
printf("\n The length of the string is : %d", length);return 0;
}
OUTPUT: Enter the string : aiml
The length of the string is : 5
Converting characters of a string into Uppercase / Lowercase
• The ASCII code for A–Z varies from 65 to 91 and the ASCII code for a–z ranges from 97 to 123.
• To convert a lower case character into uppercase Subtract 32 from the ASCII value of the character.
• To convert an upper case character into lower case Add 32 to the ASCII value of the character.
• The library functions toupper() and tolower() which are defined in ctype.h convert a character into
upper and lower case, respectively.
Write a program to convert the lower case characters of a string into upper case.
#include <stdio.h>
int main()
{
char str[100], upper_str[100];
int i=0;
printf("\n Enter the string :");
fgets(str);
while(str[i] != '\0')
{
if(str[i]>='a' && str[i]<='z')
upper_str[i] = str[i] - 32;
else
upper_str[i] = str[i];
i++;
}
upper_str[i] = '\0';
printf("\n The string converted into upper case is : ");
puts(upper_str);
return 0;
}
Appending a string to another string
• Copying the contents of the source string at the end of the destination string.
• For example, if S1 and S2 are two strings, then appending S1 to S2 means we have to add the
contents of S1 to S2. So, S1 is the source string and S2 is the destination string.
• The appending operation would leave the source string S1 unchanged and the destination string
S2 = S2 + S1.
• The library function strcat(s1, s2) which is defined in string.h concatenates string s2 to s1.
Write a program to append a string to another string.
#include <stdio.h>
int main()
{
char Dest_Str[100], Source_Str[50];
int i=0, j=0;
printf("\n Enter the source string : ");
Output
fgets(Source_Str, 50, stdin);
Enter the source string : How are
printf("\n Enter the destination string : ");
you?
fgets(Dest_Str, 100, stdin);
Enter the destination string :
while(Dest_Str[i] != '\0')
i++;
Hello,
while(Source_Str[j] != '\0') After appending, the destination
{ string is : Hello, How are you?
Dest_Str[i] = Source_Str[j];
i++;
j++;
}
Dest_Str[i] = '\0';
printf("\n After appending, the destination string is : ");
puts(Dest_Str);
return 0;
}
Comparing two strings
• If S1 and S2 are two strings, then comparing the two strings will give either of the following
results:
• To compare the two strings, each and every character is compared from both the strings. If all the
characters are the same, then the two strings are said to be equal.
• The library function strcmp(s1, s2) which is defined in string.h compares string s1 with s2.
Write a program to compare two strings
#include <stdio.h>
#include <string.h> }
int main() if(len1!=len2)
{ printf("\n The two strings are not equal");
if(same == 0)
char str1[50], str2[50];
{
int i=0, len1=0, len2=0, same=0; if(str1[i]>str2[i])
printf("\n Enter the first string : "); printf("\n String 1 is greater than string 2");
fgets(str1, 50, stdin); else if(str1[i]<str2[i])
printf("\n Enter the second string : "); printf("\n String 2 is greater than string 1");
}
fgets(str2, 50, stdin);
return 0;
len1 = strlen(str1); }
len2 = strlen(str2);
if(len1 == len2)
{
while(i<len1)
Output
{
Enter the first string : Hello
if(str1[i] == str2[i])
i++;
Enter the second string : Hello
else break;
The two strings are equal
}
if(i==len1)
{
same=1;
printf("\n The two strings are equal");
Reversing a string
• The replacement operation is used to replace the pattern P1 by another pattern P2. This is done by
writing REPLACE(text, pattern1, pattern2).
• For example,
• ("AAABBBCCC", "BBB", "X") = AAAXCCC
• ("AAABBBCCC", "X", "YYY")= AAABBBCC
• In the second example, there is no change as X does not appear in the text.
Write a program to replace a pattern with another pattern in the text
#include <stdio.h> if(pat[j]=='\0')
main() {
copy_loop=k;
{
while(rep_pat[rep_index] !='\0')
char str[200], pat[20], new_str[200], rep_pat[100]; {
int i=0, j=0, k, n=0, copy_loop=0, rep_index=0; new_str[n] = rep_pat[rep_index];
printf("\n Enter the string : "); rep_index++;
n++;
fgets(str, 200, stdin); }
printf("\n Enter the pattern to be replaced: "); }
fgets(pat, 20, stdin); new_str[n] = str[copy_loop];
i++;
printf("\n Enter the replacing pattern: "); copy_loop++;
fgets(rep_pat, 100, stdin); n++;
while(str[i]!='\0') }
new_str[n]='\0';
{
printf("\n The new string is : ");
j=0,k=i; puts(new_str);
while(str[k]==pat[j] && pat[j]!='\0’) return 0;
{
Output
k++; Enter the string : How ARE you?
j++; Enter the pattern to be replaced : ARE
} Enter the replacing pattern : are
The new string is : How are you?
Array of Strings & Memory Representation of an array of strings.
int main(){
char string1[20]; Output:
int i, length; Enter a string: madam
int flag = 0;
madam is a palindrome
printf("Enter a string:");
scanf("%s", string1);
length = strlen(string1);
if (flag) {
printf("%s is not a palindrome", string1);
}
else {
printf("%s is a palindrome", string1);
}
return 0;
}