Mastering Strings Operations in C

As we learnt that strings are special type of arrays that terminate with a NULL character. There main importance lyes in the basic operations that are performed using them. 


Learning Strings might not be a difficult task, but implementing them in different situations is much more complex and difficult task. That's why, mastering the String Operations is so much necessary while learning C programming.

We are going to learn the most fundamental operations on Strings in this blog post. These operations include :

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -

1. Length of String : Finding the length of a string is the easiest task, it can be done by 2 methods using the inbuilt strlen() function or my writing the full-fledged code. But here,we would complete the task by writing our own code, the inbuilt functions would be explained in the upcoming posts.

#include <stdio.h>
int main()
{   
    int size;
    scanf("%d",&size);
    char str[size]; 
    int i;
    int count= 0;

    printf("Enter a string: ");
    scanf("%[^\n]s,str)

    /* Iterate till the last character of string is encountered */
    for(i=0; str[i]!='\0'; i++)
    {
        count++;
    }

    printf("Length of the Entered String = %d", count);
    return 0;
}

OUTPUT

Enter a string: hello world
Length of the Entered String = 11

HOW IT WORKS : First of all, declare a variable that will give us the count of alphabets in the string. Then we need to give a input string, using scanf() or gets() or getchar(),  then a loop will iterate over each element, as the loop starts it is on the index str[0] and then in the loop body our count variable gets incremented by 1, then the 2nd iteration will work and str[1] would be reached , making the value of count = 2, this process will continue untill the last character of the string is not encountered, and the last character in every string is the \0 .
And then the loop ends. and we get the length of the string.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -

2. Converting the upper case characters to lower case : Ever heard about ASCII codes? This feature of C language, is very much helpfull in cases like this one, ASCII stands for American Standard Code for Information Interchange, it was desgined as the standard character set for electronic devices.It is a 7-bit character set containing 128 characters
  • A-Z     65-90
  • a-z      97-122
  • 0-9      48-57
These are the most widely used ASCII codes in programming, but for veiwing all the codes just click here, you would be redirected to the w3schools website for complete reference.
From the above ASCII codes its clear that between ' A ' and ' a ', there ASCII difference is 32, we can use this information in our code, just like this.

#include <stdio.h>
int main()
{
    int size;
    scanf("%d",&size);
    char str[size];
    int i;
 
    printf("Enter any string: ");
    gets(str);

    for(i=0; str[i]!='\0'; i++)
    {
        if(str[i]>='A' && str[i]<='Z')
        {
            str[i] = str[i] + 32;
        }
    }

    printf("Lower case string: %s", str);

    return 0;
}

OUTPUT

Enter any string: CoDIng
Lower case string: coding

HOW IT WORKS : This program converts all the Upper case characters into lower case, and keep the lower case characters as it is. With the help of the loop, we iterate over each character untill the \0 is not encountered, and according to the ASCII code rule 32 that we learnt above, if we increment the Uppercase character by 32, then it will become lower case as, ASCII code of 'A' is 65 and if we add 32 into it, we get 97 which is the ASCII code of 'a'.This rule helps us in this every such case. 
* Now try to make a program that changes lowercase characters of the string to the uppercase characters using this 32 rule.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -

3. Concatenating 2 strings : Concatenation means copying the elements of the 2nd string to the end of the 1st string. It is very much similar to the merging of 2 arrays, that we learnt earlier.

#include <stdio.h>
int main()
{   int size;
    scanf("%d",&size);
    char str1[size], str2[size],str3[size];
    int i, j;

    printf("Enter first string: ");
    gets(str1);
    printf("Enter second string: ");
    gets(str2);

     i=0;
    while(str1[i] != '\0')
    {
        i++;
    }

    j = 0;
    while(str2[j] != '\0')
    {
        str1[i] = str2[j];
        i++;
        j++;
    }

    str1[i] = '\0';

    printf("Concatenated string is %s", str1);

    return 0;
}

OUTPUT 
Enter first string: Hello
Enter second string: World
Concatenated string is HelloWorld

*****************
DIFFERENCE BETWEEN THE TERMS CONCATENATION AND APPENDING !
In Concatenation, a whole new string is created whereas in appending the elements of the 2nd string are copied at the end of string1, here in the above example we have used appending method. Both the methods give us the same output, but it is still important to know the actual meaning of the 2 terms. The true method to be followed is that we learnt in merging in  the arrays section. You can read it from here.
****************

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -

4. Comparing 2 strings : It implies checking whether all the elements of the 2 given strings are equal, or not. If all the elements of the 2 strings are same, then the strings are said to be equal.

#include <stdio.h>
#include<string.h>
int main()
{
    char str1[100], str2[100];
    int l1=0,l2=0,same=0,i=0;

    printf("Enter first string: ");
    gets(str1);
    printf("Enter second string: ");
    gets(str2);
    l1=strlen(str1);
    l2=strlen(str2);
    if(l1==l2)
    {
     while(i<l1)
      {
      if(str1[i] == str2[i])
       i++;
      else
        break;
       }
      if(i==l1)
      { 
      same=1;
       printf("Both are equal");
      }
    }
     if(l1!=l2)
     printf("They are not equal");
    if(same==0)
    {
     if(str1[i]>str2[i])
     printf("string1 > string 2 ");
     else if(str1[i]<str2[i])
     printf("string1 < string 2 ");
    } 
   return 0;
    
}

OUTPUT

Enter first string: coding
Enter second string: coding
Both are equal

HOW IT WORKS : This program compares each element of the strings one by one, and the strlen() function used here works with <string.h> header file.It gives us the length of the string without writing the long codes.If the length of the strings is equal.Then it will compare every element simulataneously. And if all the elements are found to be equal, then they are equal otherwise unequal.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -

5. Reversing a string : Reversing is printing the characters in the reverse order of which they are entered.

#include<stdio.h>
void main()
{
    int i, j, k;
    char str[100];
    char rev[100];
    printf("Enter a string: ");
    scanf("%s", str);
    for(i = 0; str[i] != '\0'; i++);
    {
        k = i-1;
    }
    for(j = 0; j <= i-1; j++)
    {
        rev[j] = str[k];
        k--;
    }
    printf("The reverse string is %s\n", rev);
}

OUTPUT

Enter a string: Hello
The reverse string is olleH

HOW IT WORKS : Here we firstly reverse the indexes as we know that the last element of string is NULL character, therefor a string's size is always 1 more than the actual one. So the 1st loop helps in eliminating the NULL character so that is should not be displayed in the reversed string. And the 2nd loop assigns the variables to another string created to store the reversed elements. The rev[0] stores str[5], then rev[1] stores str[4] and so on.

Ritish

Just a novice blogger

Post a Comment (0)
Previous Post Next Post