Loading...
Loading...
00:00:00

String in C Language

In c programming language there is no string data type. A string is an array of characters that is terminated by a null character \0. The null character is used to indicate the end of the string.

Strings in C are typically declared as arrays of characters, and can be initialized using a string literal or by assigning values to individual characters. For example, the following code declares a string variable and initializes it with a string literal:

char myString[] = "Hello, world!";

A string is a one-dimensional array of characters. For accessing char array we have to use index, every element in char array is char data type so we can print it using %c format specifier.

if we want to print char array as string we should use %s format specifier. For taking input string from user scanf() function may be use but scanf() is not accept white spaces, for solve this problem we can use gets() function that is declared in stdio.h header file.

Examples of char array and string:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
    // declare char array 
    char str[] = {'p','r','o','g','r','a','m','m','e','r'};
    char str0[10];
    char str1[10] = "coder";
    // assigning value in char array 
    str0[0] = 'c';
    str0[1] = ' ';
    str0[2] = 'c';
    str0[3] = 'o';
    str0[4] = 'd';
    str0[5] = 'e';
    str0[6] = '\0';
    // printing value of char array 
    for (int i = 0; i != '\0'; i++)
    {
        printf("%c",str0[i]);
    }
    printf(" The value of str is %s",str);   // programmer
    printf(" The value of str1 is %s",str1);  // coder
    printf(" The value of str0 is %s",str0);  // c code
    return 0;
}

String Functions In C

String functions are declare in string.h header file string functions:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
    char str1[] = "hello";
    char str2[] = "world";
    printf("The result is %d\n",strcmp(str1,str2));  //accroding to dictionary order
    return 0;
}

Here are some string functions:

string functions uses
strcpy() copy string variable to another
strcmp() compare two string (returns -1,0,1)
strlen() returns the length of a string
strcat() concatenate(add) two strings
strrev() reverse a string