Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Manipulation of string

A string can be manipulated using library functions as well as user defined functions.
Library functions are defined under the string.h header file.

1) Calculating string length

a) Using library function strlen()

The function strlen(), is used to calculate the length of any string.
It does not include terminating null character ‘\0′ in the length of a string.

Example
C Programming Language Calculating String Length using strlen() Function

Syntax

size_t strlen(const char *s);

Example

#include<stdio.h>
#include<string.h>
int main()
{
    char name1[15]={'J','O','H','N','\0'};
    char name2[] = "WILLIAMS";
    char name3[30];
    char *ptr = "BROWN";
    printf("\n Enter name 3 :: ");
    gets(name3);
    printf("\n Length of Name 1 = %d",strlen(name1));
    printf("\n Length of Name 2 = %d",strlen(name2));
    printf("\n Length of Name 3 = %d",strlen(name3));
    printf("\n Length of Name 4 = %d",strlen(ptr));
    return 0;
}

Output

Enter name 3 :: Robert Johnson

Length of Name 1 = 4
Length of Name 2 = 8
Length of Name 3 = 14
Length of Name 4 = 5

b) Calculating string length without using library function

Example

#include<stdio.h>
int main()
{
    int x=0,y=0;
    char city1[30] = "Delhi";
    char *city2 = "Washington";
	
    while(city1[x]!='\0')
    {
        x++;
    }
    printf("\n Length of city1 = %d",x);
	
    while(*city2!='\0')
    {
        city2++;
        y++;
    }
    printf("\n Length of city2 = %d",y);
	
    return 0;
}

Output

Length of city1 = 5
Length of city2 = 10

 

Leave a reply