C Programming

Introduction to Strings

In C language, a sequence of characters, digits and symbols enclosed within double quotes is called as string. Strings are nothing but the group of characters stored in the array wich is terminated by the NULL('\0') character. A NULL character is a byte with all bits at logic zero, so it's decimal value is zero. The character of strings are stored in a contiguous memory. Some of the examples of string are:

char str[]  = “Geeks”
or 
char str[] = {'G', 'e' , 'e', 'k', 's', '\0'}

A string can be declared as if you are declaring the array of characters. Apart from the above given examples, string can be declared as :

char str[20] ; 
Strings can be printed using printf but the format specifier must be changed to '%s' for the string. The inputs of a string can be taken using scanf with the format specifier as %s, but it cannot take multi word strings as input. So, if you want to recieve multiword strings, you can do it using scanf ( "%[^\n]s", str ) . In earlier C standards , gets can also be used for string inputs, but now gets is deprecated.

Go through the below program carefully for running example about the things we have discussed so far:

#include<stdio.h>

int main()
{
    // Basic string declaration

    // Taking string as characters
    char s[] = {'G', 'e' , 'e', 'k', 's', '\0'};
    printf("%s\n", s);

    // Taking string as a whole
    char str[] = "GeeksforGeeks";
    printf("%s\n", str);

    //Taking input in the string
    char new_string[20]; 
    scanf("%s", new_string);
    printf("%s", new_string);

    //Taking multiword string and printing it
    // NOTE : The scanf function has different format specifier
    // for multiword strings 
    scanf ( "%[^\n]s", new_string) ;
    printf("%s\n", new_string);


return 0 ;
}

With the input to the above program as GeeksforGeeks Courses.
The output is:

Geeks
GeeksforGeeks
GeeksforGeeks Courses

Recent Comments

Feedback

For any feedback,email us at feedback@geeksforgeeks.org

Report a Bug

For any report or bug,email us at support@geeksforgeeks.org