Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Strings

In this topic, we will learn different ways to manipulate strings using library functions or user-defined functions.

What is a string?

A string is a group of characters stored in contiguous memory locations.
In short, it is an array of characters with the null character ‘\0’ at the end.

char name[] = {‘J’,’O’,’H’,’N’};

Here, the name is a character array where all its elements are arranged in sequence. Therefore acts as a string of characters.

C Programming Language Character StringBut, to manipulate the string properly by using library functions or user-defined functions, it is necessary that null character ‘\0’ should be present at the end of a string.
Therefore string is terminated using ‘\0’ as shown below:

char name[] = {‘J’,’O’,’H’,’N’,’\0’};

C Programming Language Character String with Null CharacterIf we declared the size of a character array, we should take enough care that size of the array should be declared considering a null character.

If we don’t want to insert ‘\0’ manually, then we should initialize string as shown below:

char name[] = “JOHN”;

Here compiler inserts null character ‘\0’ at the end automatically.

The string can also be initialized using a pointer.

char *ptr = “JOHN”;

Here also null character ‘\0’ is inserted automatically by the compiler, as shown below:
C Programming Language String Initialized using Pointer

 

Different ways to initialize the string

char name[] = {‘J’,’O’,’H’,’N’,’\0’};

char name[] = “JOHN”;

char *ptr = “JOHN”;

Example no 1 – Using Character Array

#include<stdio.h>
int main()
{
    char name[5] = {'J','O','H','N','\0'};
    int i=0;
    while(name[i]!='\0')
    {
        printf("%c",name[i]);
        i++;
    }
    return 0;
}

Output

JOHN

Example no 2 – Using Character Array

#include<stdio.h>
int main()
{
    char name[] = "JOHN";           // ‘\0’ inserted automatically
    int i=0;
    while(name[i]!='\0')
    {
        printf("%c",name[i]);
        i++;
    }
    return 0;
}

Output

JOHN

Example no 3 – Using Pointer Variable

#include<stdio.h>
int main()
{
    char *ptr = "John";     // ‘\0’ inserted automatically  
    while(*ptr!='\0')
    {
        printf("%c",*ptr);
        ptr++;
    }
    return 0;
}

Output

John

 

Leave a reply