C has no separate "string" type. A string is an array of char that ends with the special null character '\0' (ASCII 0). That terminator is how functions like printf know where the text stops.
char city[] = "Indore";
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| Value | I |
n |
d |
o |
r |
e |
\0 |
"Indore" has 6 letters but needs 7 bytes.
Indore has 7 bytes First letter: I Changed: indore V-i-n-d-h-y-a-e-d-u-
C में string असल में char का array है जिसके आखिर में '\0' (null character) लगा होता है। इसी '\0' से पता चलता है कि string कहाँ खत्म हुई। इसलिए array का size हमेशा अक्षरों से एक ज़्यादा रखें।
Reading strings#
scanf("%s", s)- reads one word (stops at a space). No&-sis already an address.fgets(s, size, stdin)- reads a full line, including spaces and the newline.
Word: [Asha] Line: [Asha Rani Verma]
Never use gets() - it was removed from the C standard because it cannot limit the input size and lets a long input overwrite other memory (a buffer overflow, a famous security hole). Use fgets.
The string.h library#
| Function | What it does |
|---|---|
strlen(s) |
length, not counting \0 |
strcpy(dest, src) |
copy src into dest |
strncpy(dest, src, n) |
copy at most n characters |
strcat(dest, src) |
append src to the end of dest |
strcmp(a, b) |
compare: 0 if equal, <0 if a comes first, >0 otherwise |
strchr(s, c) |
pointer to the first c in s (or NULL) |
strstr(s, sub) |
pointer to the first occurrence of sub (or NULL) |
strlen(a) = 4
a = Data Science
c = Data
strcmp("abc", "abd") = -1
strcmp(c, "Data") = 0
'Sci' found inside astrcpy and strcat do not check the destination size. Make sure dest is large enough for the result plus \0.
Writing string functions yourself#
Interviewers love asking you to do these without string.h. All of them loop until '\0':
Length: 10 Upper: VINDHYAEDU Reversed: UDEAYHDNIV
Character functions: ctype.h#
isalpha, isdigit, isspace, isupper, islower, toupper, tolower:
Upper 1, lower 3, digits 4, special 1 Strong password: yes
Array of strings#
A 2D char array holds several strings - one per row:
1. Aditi 2. Kabir 3. Meera 4. Rohan
Summary#
- A string is a
chararray ending in'\0'; size = letters + 1. - Read a word with
scanf("%s"), a full line withfgets(nevergets). - Use
strlen,strcpy,strcat,strcmpfrom<string.h>- andstrcmp, not==, to compare. <ctype.h>classifies and converts characters.