Recents in Beach

String in C language for beginners

String in C language for beginners

In C language string is an one-dimensional array of characters terminated with a null character \0.

Even if we do not place the null character at the end of a string constant. The C compiler automatically places the '\0' at the end of the string when it initializes the array. Look at the following example below.

Initializing a String: A string can be initialized in different ways.

nitializing a String: A string can be initialized in different ways.

1. char str[] = "LAUNCHPADLWD";

 

2. char str[20] = "LAUNCHPADLWD";

 

3. char str[] = {'L','A','N','C','H','P','A','D','L','W','D'\0'};

 

4. char str[20] = {'L','A','N','C','H','P','A','D','L','W','D'\0'};


 memory presentation of the above string in C Language

memory representation in string

Example 1 Using printf:

#include <stdio.h>

int main()

{

    char  ch[20]=”LAUNCHPADLWD”;

    printf("%s ",ch);

    return 0;

}


String 1 example

Example 2 printing name enter by user using printf() and scanf():

#include <stdio.h>

int main()

{

    char  ch[20];

    printf(“Enter your name:”);

    scanf(“%s”,ch);

    printf("%s ",ch);

    return 0;

}


Output



Example 3 printing name enter by user using gets() and puts()

#include <stdio.h>

int main()

{

    char  ch[20];

    printf(“Enter your name:”);

    gets(ch);

    puts(ch);

    return 0;

}



Output:


We should use gets in strings because if we use scanf and user enter a name rupesh ,it will print on screen rupesh but if user enters full name rupesh jha then only rupesh will print because scanf does not read character after space so , only rupesh will print , but if we use gets then rupesh jha full name will print because gets() read the character  after space also.


To Study in detail about scanf() vs gets() Please visit this link:

https://www.launchpadlwd.xyz/search/label/C%20LANGUAGE?&max-results=8

Post a Comment

0 Comments