× Home
Next Lec → ← Previous Lec

Strings

Is string a data type in C?

What are strings

Creating string

  • We can create a character array in the following ways:
    • char name[] = "harry"; //the compiler automatically puts null character
    • char name[]= {'h','a','r','r','y','\0'}; //we have to manually put null character here

Taking string input from the user

                        

                            char str[52];
                            gets(str); //There is a function in stdio.h library called 'gets' which help us to take input from user.
                            printf("%s", str); //Either we can use printf or the code below to print the string
                            // notice above we are not using '&' as the name of the string possesses the base address of the string i.e. the address of the first element of the string. 
                            puts(str); //aliter 
                        
                    
                        

                                #include <stdio.h>
                                void printStr(char str[])
                                {
                                    int i = 0;
                                    while (str[i] != '\0')
                                    {
                                        printf("%c", str[i]);
                                        i++;
                                    }
                                    printf("\n%s\n", str); // to print whole string we use %s format specifier
                                }
                                int main()
                                {
                                    // char str[] = {'h','a','r','r','y'}; //although the program doesn't show any error but this is not valid
                                    char str[] = {'h', 'a', 'r', 'r', 'y', '\0'}; // this is valid
                                    printStr(str);
                                    // taking input form user
                                    char str2[20]; // gives error when we don't specify the length
                                    gets(str2);
                                    // printing using puts
                                    puts(str2);
                                
                                    return 0;
                                }