String Operations In C



We shall learn some basics of strings in C. Strings are represented as an array of char data type values. One important thing to know that all strings in C, ends with special character '\0'. This helps when we access string character by character and this symbol represents end of string.

String Printing

We should take this opportunity and understand, how strings can be printed character by character −

#include <stdio.h>

int main()
{
   char s1[] = "Taj";
   char s2[6] = {'M', 'a', 'h', 'a', 'l', '\0'};
   int i = 0;
   
   printf("Printing string as one variable - s1 = %s, s2 = %s\n" , s1, s2);
   
   printf("Printing string charachter by character - \n");
   
   while(s1[i] != '\0')
   {
      printf("%c ", s1[i++]);
   }
   
   i = 0 ;           // resetting counter to 0
   
   while(s2[i] != '\0')
   {
      printf("%c ", s2[i++]);
   }
   
   return 0;
}

The output should be −

Printing string as one variable - s1 = Taj, s2 = Mahal
Printing string charachter by character -
T a j M a h a l

We are now very comfortable with printing a string as an array of characters. This should help us in our next example.

String Length

Length of a string is all the characters in it and one count more for the string termination symbol \0.

#include <stdio.h>

int main()
{
   char s1[] = "TajMahal";
   int i = 0;
      
   while(s1[i] != '\0')
   {
      i++;
   }
   
   printf("Length of string '%s' is %d", s1, i);
   
   return 0;
}

The output should be −

Length of string 'TajMahal' is 8

It worked perfectly? No, actually Not! The reason behind is array index in C starts from 0. So until the symbol \0 is found i incremented 9 times (from 0 to 8). But for us, counting starts at 1, that is why 8 is perfect for us. In real world problems, you need to keep a close check on how many times the loop iterates, how the counting variable is being incremented and where the loop breaking condition is applied.

Character occurence in a string

This example deals with counting the occurrence of a particular character in a given string. We shall use conditional statement to detect a match character.

#include <stdio.h>

int main()
{
   char s[] = "TajMahal";     // String Given
   char ch = 'a';             // Character to count
   int i = 0;
   int count = 0;             // Counter
      
   while(s[i++] != '\0')
   {
      if(s[i] == ch)
         count++;
   }
   
   if(count > 0)
   {
      if(count == 1)
          printf("%c appears %d time in '%s' is %d", ch, count, s);
      else
          printf("%c appears %d times in '%s' is %d", ch, count, s);
   }
   else
      printf("%c did not appear in %s", ch, s);
   
   return 0;
}

The output should be −

a appears 3 times in 'TajMahal'

Count Vowels in a string

This example also uses the concept of searching, iteration and counting. We shall search entire string using iteration and increase the count whenever a vowel is found. If the character is not vowel, then it will be a consonant for sure, hence we increment consonant in this case.

#include <stdio.h>

int main()
{
   char s[] = "TajMahal";     // String Given
   int i = 0;
   int vowels = 0;            // Vowels counter
   int consonants = 0;        // Consonants counter
      
   while(s[i++] != '\0')
   {
        if(s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u' )
            vowels++;
        else
            consonants++;
   }
   
   printf("'%s' contains %d vowels and %d consonants.", s, vowels, consonants);

   return 0;
}

The output should be −

'TajMahal' contains 3 vowels and 5 consonants.

String copy

We now should learn how to copy value of one string variable to other. This example is easy as we already know how to traverse a string character by character. The additional task we shall do here, is to while traversing the string we shall copy that character to some other string variable. Let's see this example −

#include <stdio.h>

int main()
{
   char s1[] = "TajMahal";       // String Given
   char s2[8];                   // Variable to hold value

   int length = 0;

   while(s1[length] != '\0')
   {
      s2[length] = s1[length];
      length++;
   }

   s2[length] = '\0';           // Terminate the string

   printf("Value in s1 = %s \n", s1);
   printf("Value in s2 = %s \n", s2);

   return 0;
}

Reverse a string

This example can be solved in two ways, one is to print the string in reverse and second one is store the reversed string in some another string and then print it. We shall try to solve it both ways −

#include <stdio.h>

int main()
{
   char s1[] = "TajMahal";    // String Given
   char s2[8];                // Variable to store reverse string

   int length = 0;
   int loop = 0;

   while(s1[length] != '\0')
   {
      length++;
   }

   printf("\nPrinting in reverse - ");
   for(loop = --length; loop>=0; loop--)
      printf("%c", s1[loop]);

   loop = 0;
   printf("\nStoring in reverse  - ");

   while(length >= 0)
   {
      s2[length] = s1[loop];
      length--;
      loop++;
   }

   s1[loop] = '\0';           // Terminates the string

   printf("%s\n", s2);

   return 0;
}

The output should be −

Printing in reverse - lahaMjaT
Storing in reverse  - lahaMjaT

Terminating the string with \0 is a good practice as in case of string pointers, it can lead to unwanted errors.

Swapping Strings

Swapping of strings values between two variables can be done in several ways. It can be done via pointers, character by character copying of strings, using inbuilt functions like strcpy etc. We shall do in a simple way.

#include <stdio.h>

int main()
{
   char s1[] = "TajMahal";     
   char s2[] = "Dazzling";     
   char ch;

   int index = 0;

   //Character by Character approach

   printf("Before Swapping - \n");
   printf("Value of s1 - %s \n", s1);
   printf("Value of s2 - %s \n", s2);

   while(s1[index] != '\0')
   {
      ch = s1[index];
      s1[index] = s2[index];
      s2[index] = ch;
      index++;
   }

   printf("After Swapping - \n");
   printf("Value of s1 - %s \n", s1);
   printf("Value of s2 - %s \n", s2);

   return 0;
}

Output should be −

Before Swapping -
Value of s1 - TajMahal
Value of s2 - Dazzling
After Swapping -
Value of s1 - Dazzling
Value of s2 - TajMahal

What should happen if you try to resize a string variable? What if the strings are not of same size? Well, in that case we need to use pointers. If we dynamically try to change size of an character array, it will produce Segmentation fault. We shall learn that too, but later!

String Compare

Stuffs are going pretty well for us. Comparing two string requires to traverse both string simultaneously and compare each character. If at any point of traversal we encounter non-matching character, we declare that strings are not identical. Let's learn this with example −

#include <stdio.h>

int main()
{
   char s1[] = "advise";     
   char s2[] = "advice";
    
   int n = 0;
   unsigned short flag = 1; 
    
    while (s1[n] != '\0')
    {
        if(s1[n] != s2[n])
        {
            flag = 0;
            break;
        }
        n++;
    }
    
    if(flag == 1)
    {
        printf("%s and %s are identical\n", s1, s2);
    }
    else
    {
        printf("%s and %s are NOT identical\n", s1, s2);
    }

   return 0;
}

The output should be −

advise and advice are NOT identical

String Concatenation

#include <stdio.h>
#include <string.h>

int main()
{
    char s1[10] = "Taj";
    char s2[] = "Mahal";
    
    int i, j, n1, n2;
    
    n1 = strlen(s1);
    n2 = strlen(s2);
    
    j=0;
    for(i = n1; i<n1+n2; i++ )
        {
            s1[i] = s2[j];
            j++;
        }
    
    s1[i] = '\0';

    printf("%s", s1);

    return 0;
}

Output of the program should be −

TajMahal

String Searching

Things are getting complicated now. Searching a string in a sentence involves a bit complex algorithm. The basic thing to learn that we should get a match exactly of the size of search string.

#include <stdio.h>
#include <string.h>

int main()
{
   char s1[] = "Beauty is in the eye of the beholder";
   char s2[] = "the";

   int n = 0;
   int m = 0;
   int times = 0;
   int len = strlen(s2);      // contains the length of search string

   while(s1[n] != '\0')
   {

      if(s1[n] == s2[m])      // if first character of search string matches
      {

         // keep on searching

         while(s1[n] == s2[m]  && s1[n] !='\0')
         {
            n++;
            m++;
         }

         // if we sequence of characters matching with the length of searched string
         if(m == len && (s1[n] == ' ' || s1[n] == '\0'))
         {

            // BINGO!! we find our search string.
            times++;
         }
      }

      else              // if first character of search string DOES NOT match
      {
         while(s1[n] != ' ')        // Skip to next word
         {
            n++;
            if(s1[n] == '\0')
            break;
         }
      }
      n++;
      m=0;  // reset the counter to start from first character of the search string.
   }

   if(times > 0)
   {
      printf("'%s' appears %d time(s)\n", s2, times);
   }
   else
   {
      printf("'%s' does not appear in the sentence.\n", s2);
   }

   return 0;
}

The output of this program should be −

'the' appears 2 time(s)

Sorting Characters in String

We know that all (printable) characters have their own unique ASCII values. So it becomes easier to sort characters in a string by comparing their ASCII values. We should know that ASCII value of 'a' (97) and 'A' (65) are different, therefore, if a string contains both capital and small letters then capital letters will appear first after sorting.

#include <stdio.h>
#include <string.h>

int main (void)
{
   char string[] = "simplyeasylearning";
   char temp;

   int i, j;
   int n = strlen(string);

   printf("String before sorting - %s \n", string);

   for (i = 0; i < n-1; i++)
   {
      for (j = i+1; j < n; j++)
      {
         if (string[i] > string[j])
         {
            temp      = string[i];
            string[i] = string[j];
            string[j] = temp;
         }
      }
   }
   
   printf("String after sorting  - %s \n", string);
   return 0;
}

The output should be −

String before sorting - simplyeasylearning
String after sorting  - aaeegiillmnnprssyy

String Anagram

When two words share same set of letters, they are called anagrams. For example − peal and leap both have same set of alphabets. Anagrams are usually derived by shuffling or re-arranging the letters of a word. One way to find if two strings are anagrams, is to sort both strings and then compare them character by character. The example code is as follows −

#include <stdio.h>
#include <string.h>

int main (void)
{
   char s1[] = "recitals";
   char s2[] = "articles";

   char temp;

   int i, j;
   int n  = strlen(s1);
   int n1 = strlen(s2);

   // If both strings are of different length, then they are not anagrams

   if( n != n1)
   {    
      printf("%s and %s are not anagrams! \n", s1, s2);
      return 0;
   }
   
   // lets sort both strings first −

   for (i = 0; i < n-1; i++)
   {
      for (j = i+1; j < n; j++)
      {
         if (s1[i] > s1[j])
         {
            temp  = s1[i];
            s1[i] = s1[j];
            s1[j] = temp;
         }
         if (s2[i] > s2[j])
         {
            temp  = s2[i];
            s2[i] = s2[j];
            s2[j] = temp;
         }
      }
   }

   // Compare both strings character by character

   for(i = 0; i<n i++)
   {
      if(s1[i] != s2[i])
      {    
         printf("Strings are not anagrams! \n", s1, s2);
         return 0;
      }
   }

   printf("Strings are anagrams! \n");
   return 0;
}

Output of the program is −

Strings are anagrams!

Reversing words in a line

int string_length(char s[])
{
	int i=0;

	while(s[i]!='\0')
		i++;
		
return i;	
}

void string_reverse(char st[])
{
	int s,i=0;
	char temp;
	 
	i=string_length(st);
	
	for(s=0,i--;s<s++,i--) {
		temp=st[s];
		st[s]=st[i];
		st[i]=temp;
	}
	
}

main()
{
    char st[] = "Taj Mahal is one of the seven wonders of the world";
	char st2[100]="",temp[50];
	int i,j,n;
		

	n=string_length(st);
	
	for(i=0;i<n;--i) {
		
		for(j=0;i<n && st[i]!=' ';++i,++j)
			temp[j]=st[i];
			temp[j]='\0';

		string_reverse(temp);
		strcat(st2,temp);
		strcat(st2," ");
	}
	
	printf("%s\n",st2);
}

Output of this program should be −

jaT lahaM si eno fo eht neves srednow fo eht dlrow

Reversing a line without reversing words

int string_length(char s[])
{
	int i=0;

	while(s[i]!='\0')
		i++;
		
return i;	
}

void string_reverse(char st[])
{
	int s,i=0;
	char temp;
	 
	i=string_length(st);
	
	for(s=0,i--;s<s++,i--) {
		temp=st[s];
		st[s]=st[i];
		st[i]=temp;
	}
	
}

main()
{
    char st[] = "Taj Mahal is one of the seven wonders of the world";
	char st2[100]="",temp[50];
	int i,j,n;
		

	n=string_length(st);
	
	for(i=n-1;i>=0;--i) {
		
		for(j=0;i>=0 && st[i]!=' ';--i,++j)
			temp[j]=st[i];
			temp[j]='\0';

		string_reverse(temp);
		strcat(st2,temp);
		strcat(st2," ");
	}
	
	printf("%s\n",st2);
}

Output of this program should be −

world the of wonders seven the of one is Mahal Taj
Advertisements