Previous | Home | Next |
String in C is an array of char values which terminated by a special null character value '\0'. '\0' indicates the end of the string. So when you define a string you should be sure to have sufficient space for the null terminator. In ASCII table, the null terminator has value 0. Strings are always enclosed by double quotes. Whereas, character is enclosed by single quotes in C.
# Some Points
- String are one-dimensional Array
- string in/output: printf("%s",S), scanf("%s",S)
- <string.h> : Collection of functions for string manipulation
Let us create a string consisting of the word "hellor4r". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "hellor4r."
String can be initialized in different number of ways. When define string you should have extra space for '\0'(null character)
char string[9] = {'H', 'e', 'l', 'l', 'o','r','4','r', '\0'}; /* OR */ /* character is enclosed by single quotes */ char string[] = {'H', 'e', 'l', 'l', 'o','r','4','r', '\0'}; /* OR */ /* strings are always enclosed by double quotes */ char string[] = "Hellor4r"; /* OR */ char string[9] = "Hellor4r";
Following is the memory presentation of above defined string in C
Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
Variable | H | e | l | l | o | r | 4 | r | '\0' |
Address | 0x26461 | 0x26462 | 0x26463 | 0x26464 | 0x26465 | 0x26466 | 0x26467 | 0x26468 | 0x26469 |
C program to illustrate how to read string from terminal.
#include <stdio.h> int main() { char name[20]; printf("Enter name: "); scanf("%s",name); printf("Your name is %s.",name); return 0; }
Enter name: XYZ PQR
Your name is XYZ.
Here, program will ignore PQR because, scanf() function takes only string before the white space. Now use getchar() function to to read line of text manually.
#include <stdio.h> int main() { char name[30],ch; int i=0; printf("Enter name: "); while(ch!='\n') // terminates if user hit enter { ch=getchar(); name[i]=ch; i++; } name[i]='\0'; // inserting null character at end printf("Name: %s",name); return 0; }
Enter name: XYZ PQR
Your name is XYZ PQR.
Note: There are predefined functions gets() and puts in C language to read and display string respectively.
Previous | Home | Next |