Programming in C: Unit II (b): Strings

Operations on Strings

Syntax with Example C Programs

In this section, we will learn about different operations that can be performed on character arrays. But before we start with these operations, we must understand the way arithmetic operators can be applied to characters.

OPERATIONS ON STRINGS

In this section, we will learn about different operations that can be performed on character arrays. But before we start with these operations, we must understand the way arithmetic operators can be applied to characters.

In C, characters can be manipulated in the same way as we do with numbers. When we use a character constant or a character variable in an expression, it is automatically converted into an integer value, where the value depends on the local character set of the system. For example, if we write

int i;

char ch 'A';

i = ch;

printf("%d", i);

// Prints 65, ASCII value of ch is 'A'

C also enables programmers to perform arithmetic operations on character variables and character constants. So, if we write

int i;

char ch = 'A';

i = ch + 10;

printf("%d", i);

// Prints 75, ASCII value of ch that is 'A' + 10

Character variables and character constants can be used with relational operators as shown in the example below,

char ch = 'C';

if (ch >= 'A' && ch <= 'Z')

printf("The character is in upper case");

Finding the Length of a String

The number of characters in the string constitutes the length of the string. For example, LENGTH ("C PROGRAMMING IS FUN") will return 19. Note that even blank spaces are counted as characters in the string.

LENGTH('0') = 0 and LENGTH(‘’) = 0 because both the strings do not contain any character and the ASCII code of ‘ \0’  is zero. Therefore, both the strings are empty and of zero length. Figure 6.6 shows an algorithm that calculates the length of a string.

In this algorithm, I is used as an index of the string STR. To traverse each and every character of STR we increment the value of I. Once the null character is encountered, the control jumps out of the while loop and length is initialized with the value of I. This is because the number of characters in the string constitutes its length.

Note

There is a library function strlen(s1) that returns the length of s1. It is defined in string.h.

3. Write a program to find the length of a string.

#include <stdio.h>

#include <conio.h>

int main()

{

char str[100], i = 0, length;

clrscr();

printf("\n Enter the string :");

gets (str);

while (str[i] != '\0')

i++;

length= i;

printf("\n The length of the string is : %d", length);

getch();

return 0;

}

Output

Enter the string: HELLO

The length of the string is: 5

Converting Characters of a String into Upper Case

We have already seen that in memory the ASCII codes are stored instead of the real value. The ASCII code for A-Z varies from 65 to 91 and the ASCII code for a-z ranges from 97 to 123. So if we have to convert a lower case character to upper case, then we just need to subtract 32 from the ASCII value of the character. Figure 6.7 shows an algorithm that converts characters of a string into upper case.

Note

There is a library function toupper() that converts a character into upper case. It is defined in ctype.h

In the algorithm, we initialize I to zero. Using I as the index of STR, we traverse each character from Step 2 to 3. If the character is already in upper case, then it is copied in Upperstr else the lower case character is converted into upper case by subtracting 32 from its ASCII value. The upper case character is then stored in Upperstr. Finally, when all the characters have been traversed a null character is appended to Upperstr (as done in Step 4).

4. Write a program to convert characters of a string to upper case.

#include <stdio.h>

#include <conio.h>

int main()

{

char str [100], upper_str [100];

int i=0, j=0;

clrscr();

printf("\n Enter the string: ");

gets (str);

while (str[i] != '\0')

{

if (str[i] >='a' && str[i] <= 'z')

upper_str[j] = str[i] -32;

else

upper_str[j] = str[i];

i++; j++;

}

upper_str[j] = '\0';

printf("\n The string converted into upper case is: ");

puts (upper_str);

return 0;

}

Output

Enter the string: hello

The string converted into upper case is: HELLO

Converting Characters of a String Into Lower Case

If we have to convert an upper case character into lower case, then we just need to add 32 to its ASCII value. Figure 6.8 shows an algorithm that converts characters of a string into lower case.

Note

In C, there is a library function tolower() that converts a character into lower case. It is defined in ctype.h

In the algorithm, we initialize I to zero. Using I as the index of STR, we traverse each character from Step 2 to 3. If the character is already in lower case, then it is copied in Lowerstr else the upper case character is converted into lower case by adding 32 to its ASCII value. The lower case character is then stored in Lowerstr. Finally, when all the characters have been traversed a null character is appended to Lowerstr (as done in Step 4).

5. Write a program to convert characters of a string into lower case.

#include <stdio.h>

#include <conio.h>

int main()

{

char str[100], lower_str [100];

int i = 0, j = 0;

clrscr();

printf("\n Enter the string :");

gets (str);

while (str[i] != '\0')

{

if (str[i] >='A' && str[i] <= 'Z')

lower_str[j] str[i] + 32;

else

lower_str[j] = str[i];

i++; j++;

}

lower_str[j] = '\0';

printf("\n The string converted into lower case is : ");

puts (lower_str);

return 0;

}

Output

Enter the string: HeLLo

The string converted into lower case is: hello

Concatenating Two Strings to Form a New String

If S1 and S2 are two strings, then concatenation operation produces a string which contains characters of S1 followed by the characters of s2. Figure 6.9 shows an algorithm that concatenates two strings.

In this algorithm, we first initialize the two counters I and J to zero. To concatenate the strings, we have to copy the contents of the first string followed by the contents of the second string in a third string, new_str. Steps 2 to 4 copies the contents of the first string in new_str. Likewise, Steps 6 to 8 copies the contents of the second string in new_str. After the contents have been copied a null character is appended at the end of new_str.

6. Write a program to concatenate two strings.

#include <stdio.h>

#include <conio.h>

int main()

{

char str1 [100], str2 [100], str3 [100];

int i=0, j=0;

clrscr();

printf("\n Enter the first string : ");

gets (strl);

printf("\n Enter the second string: ");

gets (str2);

while (strl [i] != '\0')

{

str3 [j] = strl [i];

i++;

j++;

}

i=0;

while (str2 [i] != '\0')

{

str3 [j] = str2 [i];

i++;

j++;

}

str3 [j] = '\0';

printf("\n The concatenated string is: ");

puts (str3);

getch();

return 0;

}

Output

Enter the first string: Hello,

Enter the second string: How are you?

The concatenated string is: Hello, How are you?

Appending a String to Another String

Appending one string to another string involves 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. Here S1 is the source string and S2 is the destination string. The append operation would leave the source string S1 unchanged and destination string S2 = S2+ S1. Figure 6.10 shows an algorithm that appends two strings.

Note

There is a library function strcat(s1, s2) that concatenates s2 to s1. It is defined in string.h.

In this algorithm, we first traverse through the destination string to reach its end, i.e., reach the position where a null character is encountered. The characters of the source string are then copied into the destination string starting from that position. Finally, a null character is added to terminate the destination string.

7. Write a program to append a string to another string

#include <stdio.h>

#include <conio.h>

int main()

{

char Dest_Str [100], Source_Str [50];

int i = 0, j = 0;

clrscr();

printf("\n Enter the source string: ");

gets (Source_Str);

printf("\n Enter the destination string: ");

gets (Dest_Str);

while (Dest_Str[i] != '\0')

i++;

while (Source Str[j] != '\0')

{

Dest_Str[i] = Source_Str[j];

i++;

j++;

}

Dest Str[i] = '\0';

printf("\n After appending, the destination string is: ");

puts (Dest_Str);

getch();

return 0;

}

Output

Enter the source string: How are you?

Enter the destination string: Hi,

After appending, the destination string is: Hi, How are you?

Comparing Two Strings

If S1 and S2 are two strings then comparing two strings will give either of these results:

(a) S1 and S2 are equal

(b) S1 > S2, when in dictionary order S1 will come after S2

(c) S1 < S2, when in dictionary order S1 precedes S2

To compare the two strings, each and every character is compared from both the strings. If all the characters are same then the two strings are said to be equal. Figure 6.11 shows an algorithm that compares two strings.

Note

There is a library function strcmp (s1, s2) that compares s2 with s1. It is defined in string.h.

In this algorithm, we first check whether the two strings are of same length. If not, then there is no point in moving ahead as it straightaway means that the two strings are not same. However, if the two strings are of the same length, then we compare character by character to check if all the characters are same. If yes, then variable SAME is set to 1 else if SAME = 0, then we check which string precedes the other in dictionary order and print the corresponding message.

8. Write a program to compare two strings.

#include <stdio.h>

#include <conio.h>

#include <string.h>

int main()

{

char str1 [50], str2 [50];

int i=0, len1 = 0, len2 = 0;

 clrscr();

printf("\n Enter the first string: ");

gets (strl);

printf("\n Enter the second string :

gets (str2);

len1 = strlen(strl);

len2 = strlen(str2);

if (lenl = = len2)

{

while(i<len1)

{

if (strl [i] = = str2 [i])

i++;

else break;

}

if (i==lenl)

{

same = 1;

printf("\n The two strings are equal");

}

}

if (lenl!=len2)

printf("\n The two strings are not equal");

if (same = = 0)

{

if (strl [i] >str2 [i])

printf("\n String1 is greater than string2");

else if (str1 [i] <str2 [i])

printf("\n String2 is greater than string1");

}

getch();

return 0;

}

Output

Enter the first string: Hello

Enter the second string: Hello

The two strings are equal

Reversing a String

If S1= "HELLO", then reverse of S1 = "OLLEH". To reverse a string we just need to swap the first character with the last, second character with the second last character, so on and so forth. Figure 6.12 shows an algorithm that reverses a string.

Note

There is a library function strrev(s1) that reverses all the characters in the string except the null character. It is defined in string.h.

In Step 1, I is initialized to zero and J is initialized to the length of the string STR -1. In Step 2, a while loop is executed until all the characters of the string are accessed. In Step 3, we swap the ith character of STR with its jth character. (As a result, the first character of STR will be interchanged with the last character, the second character will be interchanged with the second last character of STR, and so on). In Step 4, the value of I is incremented and J is decremented to traverse STR in the forward and backward direction, respectively.

9. Write a program to reverse the given string.

#include <stdio.h>

#include <conio.h>

#include <string.h>

int main()

{

char str[100], temp;

int i = 0, j = 0;

clrscr();

printf("\n Enter the string: ");

gets (str);

j = strlen(str) -1;

while (i<j)

{

temp = str[j];

str[j] = str[i];

str[i] = temp;

i++;

j--;

}

printf("\n The reversed string is: ");

puts (str);

getch();

return 0;

}

Output

Enter the string: Hi there

The reversed string is: ereht iH

Extracting a Substring from Left

In order to extract a substring from the main string we need to copy the content of the string starting from the first position to the nth position where n is the number of characters to be extracted.

For example, if S1 = "Hello World", then Substr_ s1 Left (S1, 7) = Hello W

Figure 6.13 shows an algorithm that extracts the first n characters from a string.

In Step 1, we initialize the index variable I with zero. In Step 2, a while loop is executed until all the characters of STR have been accessed and I is less than N. In Step 3, the Ith character of STR is copied in the Ith character of Substr. In Step 4, the value of I is incremented to access the next character in STR. In Step 5, Substr is appended with a null character.

10. Write a program to extract the first N characters of a string.

#include <stdio.h>

#include <conio.h>

int main()

{

char str[100], substr [100];

int i=0, n;

clrscr();

printf("\n Enter the string: ");

gets (str);

printf("\n Enter the number of characters to be copied: ");

scanf("%d", &n);

i = 0;

while (str[i] != '\0' && i< n)

{

substr[i] = str[i];

i++;

}

substr [i] = '\0';

printf("\n The substring is: ");

puts (substr);

getch();

return 0;

}

Output

Enter the string: Hi there

Enter the number of characters to be copied: 2

The substring is: Hi

Extracting a Substring from Right of the String

In order to extract a substring from the right side of the main string we need to first calculate the position from the left. For example, if s1 = "Hello World" and we have to copy 7 characters starting from the right, then we have to actually start extracting characters from the 4th position. This is calculated by total number of characters For example, if S1 = "Hello World", then Substr_ Right (S1, 7) = o World

Figure 6.14 shows an algorithm that extracts n characters from the right of a string.

In Step 1, we initialize the index variable I to zero and J to Length (STR) - N, so that J points to the character from which the string has to be copied in the substring. In Step 2, a while loop is executed until the null character in STR is accessed. In Step 3, the Jth character of STR is copied in the 1th character of Substr. In Step 4, the value of I and J are incremented. In Step 5, Substr is appended with a null character.

11. Write a program to extract the last N characters of a string.

#include <stdio.h>

#include <conio.h>

int main()

{

char str[100], substr [100];

int i=0, j=0, n;

clrscr();

printf("\n Enter the string: ");

gets (str);

printf("\n Enter the number of characters to be copied: ");

scanf("%d", &n);

j = strlen(str) - n;

while(str[j] != '\0')

{

substr [i] = str[j];

i++, j++;

}

substr [i] = '\0';

printf("\n The substring is: ");

puts (substr);

getch();

return 0;

}

Output

Enter the string : Hi there

Enter the number of characters to be be copied : 5

The substring is: there

Extracting a Substring from the Middle of a String

To extract a substring from a given string requires information about three things. The main string, the position of the first character of the substring in the given string, and the number of characters/length of the substring. For example, if we have a string,

str[] = "Welcome to the world of programming";

then,

SUBSTRING (str, 15, 5) = world

Figure 6.15 shows an algorithm that extracts the substring from a middle of a string.

In this algorithm, we initialize a loop counter I to M, i.e., the position from which the characters have to be copied. Steps 3 to 6 are repeated until N characters have been copied. With every character copied, we decrement the value of N. The characters of the string are copied into another string called substr. At the end a null character is appended to substr to terminate the string.

12. Write a program to extract a substring from a given string.

#include <stdio.h>

#include <conio.h>

int main()

{

char str[100], substr [100];

int i=0, j=0, n, m;

clrscr();

printf("\n Enter the main string: ");

gets (str);

printf("\n Enter the position from which to start the substring: ");

scanf("%d", &m);

printf("\n Enter the length of the substring: ");

scanf("%d", &n);

i=m;

while (str[i] != '\0' && n>0)

{

substr[j] = substr[j]

i++;

j++;

n--;

}

substr[j] = '\0';

printf("\n The substring is: ");

puts (str);

getch();

return 0;

}

Output

Enter the main string : Hi there

Enter the position from which to start the substring: 1

Enter the length of the substring: 7

The substring is : i there

Inserting a String in Another String

The insertion operation inserts a string s in the main text T at kth position. The general syntax of this operation is: INSERT (text, position, string). For example, INSERT ("XYZXYZ", 3, "AAA") "XYZAAAXYZ"

Figure 6.16 shows an algorithm to insert a string in a given text at the specified position.

Programming Tip: A program must include stdio.h for standard I/O operations, ctype.h for character handling functions, string.h for string functions, and stdlib.h for other general utility functions.

This algorithm first initializes the indexes in the string to zero. From Steps 3 to 4, the contents of new_str are built. If I is exactly equal to the position at which the substring has to be inserted into the text, then the inner loop copies the contents of the substring into the new_str. Otherwise, the contents of the text are copied into it.

13. Write a program to insert a string in the main text.

#include <stdio.h>

#include <conio.h>

int main()

{

char text [100], str[20], ins_text [100];

int i=0, j=0, k=0,pos;

clrscr();

printf("\n Enter the main text : ");

gets (text);

printf("\n Enter the string to be inserted: ");

gets (str);

printf("\n Enter the position at which the string has to be inserted: ");

scanf("%d", &pos);

while (text [i]!='\0')

if (i==pos)

{

while (str [k] != '\0')

{

ins_text [j]=str [k];

j++;

k++;

}

}

else

{

ins_text [j]=text [i];

j++;

}

i++;

}

ins_text [j]='\0';

printf("\n The new string is: ");

puts (ins_text);

getch();

return 0;

}

Output

Enter the main text: How you?

Enter the string to be inserted: are

Enter the position at which the string has to be inserted: 6

The new string is: How are you?

Indexing

Index operation returns the position in the string where the string pattern first occurs. For example,

INDEX ("Welcome to the world of programming", "world") = 15

However, if the pattern does not exist in the string, the INDEX function returns 0. Figure 6.17 shows an algorithm to find the index of the first occurrence of a string within a given text.

In this algorithm, MAX is initialized to LENGTH (text) - Length (str) + 1. Take for example, if a text contains- "Welcome To Programming" and the string contains "World". In the main text we will look for at the most 22 - 5 + 1 = 18 characters because after that there is no scope left for the string to be present in the text.

Steps 3 to 6 are repeated until each and every character of the text has been checked for the occurrence of the string within it. In the inner loop, in Step 3, we check n characters of string with n characters of text to find if the characters are same. If it is not the case, then we move to Step 6, where I is incremented. If the string is found, index is initialized with I else set to -1. For example, if

TEXT = WELCOME TO THE WORLD

STRING = COME

In the first pass of the inner loop, we will compare WELC with COME character by character. As soon as w and c do not match, the control will move to Step 6 and then ELCO will be compared with COME. In the next pass, LCOM will be compared with COME.

We will write the programming code of indexing operation in the operations that follows.

Deleting a String from the Main String

The deletion operation deletes a substring from a given text. We write it as, DELETE (text, position, length). For example,

DELETE ("ABCDXXXABCD", 4, 3) ="ABCDABCD"


In this algorithm, we first initialize indexes to zero. Steps 3 to 6 are repeated until all the characters of the text are scanned. If I is exactly equal to M, the position from which deletion has to be done, then the index of the text is incremented and N is decremented. N is the number of characters that have to be deleted starting from position M. However, if I is not equal to M, then the characters of the text are simply copied into the new_str.

Delete operation can also be used to delete a string from a given text. To do this, we first find out the first index at which the string occurs in the text. Then we delete n number of characters from the text, where n is the number of characters in the string.

14. Write a program to delete a substring from a text.

#include <stdio.h>

#include <conio.h>

int main()

{

char text [200], str [20], new_text [200];

int i=0, j=0, k, n=0, copy_loop=0;

clrscr();

printf("\n Enter the main text: ");

gets (text);

printf("\n Enter the string to be deleted: ");

gets (str);

while (text [i]!='\0')

{

j=0, k=i;

while (text [k] ==str[j] && str[j] !='\0')

{

K++;

j++;

}

if (str[j]=='\0')

copy_loop=k;

new_text [n] = text [copy_loop];

i++;

copy_loop++;

n++;

}

new_str [n] = '\0';

printf("\n The new string is: ");

puts (new_text);

getch();

return 0;

}

Output

Enter the main text: Hello, how are you?

Enter the string to be deleted:, how are you?

The new string is: Hello

Replacing a Pattern with Another Pattern in a String

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. Figure 6.19 shows an algorithm to replace a pattern P1 with another pattern P2 in the text.

The algorithm is very simple, where we first find the position Pos, at which the pattern occurs in the text, then delete the existing pattern from that position, and insert a new pattern  there. String matching refers to finding occurrences of a pattern string within another string.

15. Write a program to replace a pattern with another pattern in the text.

#include <stdio.h>

#include <conio.h>

int main()

{

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;

clrscr();

printf("\n Enter the string: ");

gets (str);

printf("\n Enter the pattern to be replaced: ");

gets (pat);

printf("\n Enter the replacing pattern: ");

gets (rep_pat);

while (str[i]!= '\0')

{

j=0,k=i;

while (str [k] ==pat [j] && pat [j] != '\0')

{

k++;

j++;

}

if (pat [j]=='\0')

{

copy_loop=k;

while (rep_pat [rep_index] != '\0')

}

new_str [n] = rep_pat [rep_index];

rep_index++;

n++;

}

}

new_str [n] = str[copy_loop];

i++;

copy_loop++;

n++;

}

new_str[n] = ' \0';

printf("\n The new string is: ");         

puts (new_str);

getch();

return 0;

}

Output

Enter the string: How ARE you?

Enter the pattern to be replaced: ARE

Enter the replacing pattern: are

The new string is : How are you?

Programming in C: Unit II (b): Strings : Tag: : Syntax with Example C Programs - Operations on Strings