Strings in C Programming Language
A string in C is a series of characters in a group that occupy contiguous memory. A group of characters (Alphabets, digits and special characters) is called as a string.
“Thank you for visiting www.learnconline.com” “www.learnconline.com is excellent site for beginners. This is example of strings in C.”
A string in C should always be enclosed with in double quotes (“).
If single quote is used then it is treated as character. Hence ‘A’ is different from “A”. Every string ends with a null character (‘\0’). Note that \0 is a single character. So when it has to be explicitly assigned to a string, it has to be written with in single quotes as ‘\0’.
A null character occupies 1 byte of memory.
The above statement declares an array named “name” capable of holding 20 characters. The 20th character is null character. Hence we can store 19 characters. The 20th character is reserved for null character.
‘L’ is stored at name
‘e’ is stored at name
‘a’ is stored at name
‘r’ is stored at name
‘e’ is stored at name
‘\0’ is stored at name.
name and name will contain garbage value.
char name=”Learn C Online”;
Here the size of an array is calculated automatically (15 characters).
We can also declare string as character pointer as follows:
char *name = “Learn C Online”;
Using Character pointer:
char *name = "Learn C Online"; printf(name); printf("%s", name); printf("%s",&name);
Using Character Array:
char name="Learn C Online"; printf(name); printf(“%s”, name); printf(“%s”,&name);
printf function can be used to print a string in C. Similarly, puts function can be used to print a string as shown below.
char name=”Learn C Online”; puts(name);
Accepting String as input in C language:
We can use scanf or gets to accepts string from the user.
Using scanf in C:
The above statement passes the base address implicitly.
In the above statement, we are passing the address of the first element.
Using gets in C:
Although scanf and gets seems to be the same, there is a big difference between them. Let’s understand this difference.
Program using scanf in C language:
char *str; printf("Enter the string: "); scanf("%s",str); printf("\n%s",str);
Enter the string: Learn C Online Learn
Program using gets in C language:
char *str; printf("Enter the string: "); gets(str); printf("\n%s",str);
Enter the string: Learn C Online Learn C Online
When a string in C is accepted using scanf function, if a space is encountered then it will treat it as null character(‘\0’). In the above example, a space encountered after “Learn” is treated as null character. Hence while printing, only “Learn” is printed.
This problem can be resolved using gets function.