Chapter 7 – Strings in C Language
Introduction
In many programs, we need to work with text such as names, addresses, messages, and sentences. In C language, text is commonly represented using strings.
A string is a sequence of characters stored in a character array. Unlike some other programming languages, C does not have a separate built-in string data type. Instead, strings are stored using arrays of the char data type.
In this chapter, you will learn how to declare, initialize, input, display, compare, copy, and manipulate strings in C.
1. What is a String?
A string is a sequence of characters terminated by a special character called the null character.
The null character is written as:
'\0'
For example:
char name[] = "GWALNET";
Internally, it is stored approximately as:
G W A L N E T \0
The '\0' tells C where the string ends.
2. Character vs String
A single character is enclosed in single quotation marks.
char grade = 'A';
A string is enclosed in double quotation marks.
char name[] = "Dharmendra";
Difference
| Character | String |
|---|---|
| 'A' | "A" |
| Stores one character | Stores a sequence of characters |
| Uses single quotes | Uses double quotes |
| Example: char ch | Example: char name[] |
3. Declaring a String
Since C stores strings in character arrays, we can declare a string as:
char name[20];
This creates space for characters.
Another method is:
char city[] = "Guna";
The compiler determines the required size automatically.
4. Initializing a String
A string can be initialized in two common ways.
Method 1: String literal
char name[] = "Gwalnet";
Method 2: Character-by-character
char name[] = {'G', 'w', 'a', 'l', 'n', 'e', 't', '\0'};
Both represent the same sequence of characters.
5. The Null Character
The null character:
'\0'
is important because it marks the end of a C string.
For example:
char word[] = "Hello";
Conceptually, the array contains:
H e l l o \0
There are five visible characters, but the array requires space for the terminating null character as well.
6. Displaying a String
The %s format specifier is used with printf() to display a string.
#include <stdio.h> int main() { char name[] = "GWALNET"; printf("%s", name); return 0; }
Output
GWALNET
7. Taking a String as Input
The scanf() function can be used to read a simple string without spaces.
#include <stdio.h> int main() { char name[30]; printf("Enter your name: "); scanf("%29s", name); printf("Hello %s", name); return 0; }
If the user enters:
Rahul
the output will be:
Hello Rahul
Important
When using %s with an array, we normally write:
scanf("%29s", name);
rather than:
scanf("%29s", &name);
The array name already provides the appropriate address for this use.
8. Reading a Sentence
scanf("%s", ...) stops reading when it encounters whitespace. Therefore, it is not suitable for reading a complete sentence containing spaces.
For line-based input, fgets() is a better choice.
#include <stdio.h> int main() { char sentence[100]; printf("Enter a sentence: "); fgets(sentence, sizeof(sentence), stdin); printf("You entered: %s", sentence); return 0; }
fgets() can read spaces as part of the input.
9. String Length
The strlen() function is used to find the length of a string.
It is available in:
#include <string.h>
Example
#include <stdio.h> #include <string.h> int main() { char name[] = "GWALNET"; printf("Length = %zu", strlen(name)); return 0; }
Output
Length = 7
The null character is not counted as part of the string length.
10. Copying Strings
The strcpy() function can be used to copy one string into another character array.
#include <stdio.h> #include <string.h> int main() { char source[] = "Computer"; char destination[20]; strcpy(destination, source); printf("%s", destination); return 0; }
Output
Computer
Important
The destination array must have enough space for the copied string, including the terminating null character.
11. Joining Strings
The strcat() function is used to append one string to another.
#include <stdio.h> #include <string.h> int main() { char first[30] = "Hello "; char second[] = "World"; strcat(first, second); printf("%s", first); return 0; }
Output
Hello World
The destination array must have sufficient capacity for the combined string.
12. Comparing Strings
The strcmp() function compares two strings.
#include <stdio.h> #include <string.h> int main() { char first[] = "Apple"; char second[] = "Apple"; if(strcmp(first, second) == 0) { printf("Strings are equal"); } else { printf("Strings are different"); } return 0; }
Output
Strings are equal
General result of strcmp()
0 → strings are equal
Less than 0 → first string is ordered before the second
Greater than 0 → first string is ordered after the second
Do not assume that every non-zero result will be exactly -1 or 1.
13. Common String Functions
The <string.h> header provides several useful string functions.
| Function | Purpose |
|---|---|
| strlen() | Finds string length |
| strcpy() | Copies a string |
| strcat() | Appends one string to another |
| strcmp() | Compares two strings |
Example:
#include <string.h>
should be included when these standard string functions are used.
14. Printing Characters of a String
A string is an array of characters, so we can process it using a loop.
#include <stdio.h> int main() { char word[] = "HELLO"; int i; for(i = 0; word[i] != '\0'; i++) { printf("%c\n", word[i]); } return 0; }
Output
H E L L O
The loop continues until it reaches the null character.
15. Counting Characters Without strlen()
We can calculate the length of a string manually.
#include <stdio.h> int main() { char text[] = "Programming"; int i = 0; while(text[i] != '\0') { i++; } printf("Length = %d", i); return 0; }
Output
Length = 11
This example demonstrates how a string is actually processed internally.
16. Converting a String to Uppercase
The toupper() function can convert a character to uppercase.
It is provided by:
#include <ctype.h>
Example:
#include <stdio.h> #include <ctype.h> int main() { char text[] = "hello"; int i; for(i = 0; text[i] != '\0'; i++) { text[i] = (char)toupper((unsigned char)text[i]); } printf("%s", text); return 0; }
Output
HELLO
17. Converting a String to Lowercase
The tolower() function converts a character to lowercase.
#include <stdio.h> #include <ctype.h> int main() { char text[] = "HELLO"; int i; for(i = 0; text[i] != '\0'; i++) { text[i] = (char)tolower((unsigned char)text[i]); } printf("%s", text); return 0; }
Output
hello
18. Reversing a String
A string can be processed from the last character toward the first.
Example:
#include <stdio.h> #include <string.h> int main() { char text[] = "HELLO"; int i; for(i = (int)strlen(text) - 1; i >= 0; i--) { printf("%c", text[i]); } return 0; }
Output
OLLEH
This example displays the characters in reverse order without modifying the original string.
19. Finding Vowels in a String
We can use a loop and conditional statements to count vowels.
#include <stdio.h> int main() { char text[] = "computer"; int i; int count = 0; for(i = 0; text[i] != '\0'; i++) { if(text[i] == 'a' || text[i] == 'e' || text[i] == 'i' || text[i] == 'o' || text[i] == 'u') { count++; } } printf("Number of vowels = %d", count); return 0; }
Output
Number of vowels = 3
20. Array of Strings
We can store multiple strings using a two-dimensional character array.
Example:
#include <stdio.h> int main() { char names[3][20] = { "Aman", "Riya", "Karan" }; int i; for(i = 0; i < 3; i++) { printf("%s\n", names[i]); } return 0; }
Output
Aman Riya Karan
Here, each row stores one string.
21. String and Array Relationship
A C string is essentially a character array terminated by '\0'.
For example:
char city[] = "Guna";
Conceptually:
Index 0 1 2 3 4 ↓ ↓ ↓ ↓ ↓ Character G u n a \0
This relationship is important for understanding how string operations work in C.
22. Important Input Safety Point
When reading input into a character array, make sure the destination array has enough space.
For example:
char name[20];
can hold at most 19 ordinary characters plus the terminating '\0' when storing a normal C string.
For scanf(), a width can be used:
scanf("%19s", name);
For reading a complete line:
fgets(name, sizeof(name), stdin);
Using appropriate input limits helps prevent writing beyond the bounds of the array.
23. Common Mistakes with Strings
Mistake 1: Using single quotes for a string
Incorrect:
char name[] = 'Hello';
Correct:
char name[] = "Hello";
Mistake 2: Forgetting the null terminator
When manually constructing a C string character by character, make sure there is enough space for '\0'.
char word[] = {'H', 'i', '\0'};
Mistake 3: Comparing strings with ==
This is not the normal way to compare the contents of two C strings.
Instead, use:
strcmp(first, second)
Mistake 4: Not providing enough destination space
Functions such as strcpy() and strcat() require the destination array to have enough capacity.
24. Difference Between Character and String
char ch = 'A';
stores one character.
char text[] = "A";
stores a string containing the character A followed by the null character.
Conceptually:
'A' → one character "A" → 'A' + '\0'
25. Useful String Functions – Quick Reference
| Function | Header | Use |
|---|---|---|
| strlen() | <string.h> | Find length |
| strcpy() | <string.h> | Copy string |
| strcat() | <string.h> | Join/append strings |
| strcmp() | <string.h> | Compare strings |
| toupper() | <ctype.h> | Convert character to uppercase |
| tolower() | <ctype.h> | Convert character to lowercase |
26. Practice Programs
Try writing C programs to:
Find the length of a string.
Count vowels in a string.
Count consonants in a string.
Count digits in a string.
Count spaces in a sentence.
Convert lowercase letters to uppercase.
Convert uppercase letters to lowercase.
Copy one string into another.
Compare two strings.
Concatenate two strings.
Display a string in reverse order.
Count the number of words in a sentence.
27. Practice MCQs
Question 1
Which header file contains standard string functions such as strlen() and strcmp()?
A. <stdio.h>
B. <string.h>
C. <stdlib.h>
D. <math.h>
Answer: B. <string.h>
Question 2
Which character marks the end of a C string?
A. '\n'
B. ' '
C. '\0'
D. '\t'
Answer: C. '\0'
Question 3
Which format specifier is commonly used to print a string?
A. %c
B. %d
C. %f
D. %s
Answer: D. %s
Question 4
Which function finds the length of a string?
A. strcpy()
B. strlen()
C. strcmp()
D. strcat()
Answer: B. strlen()
Question 5
Which function compares two strings?
A. strcmp()
B. strcpy()
C. strlen()
D. strcat()
Answer: A. strcmp()
Question 6
Which function appends one string to another?
A. strlen()
B. strcmp()
C. strcat()
D. strcpy()
Answer: C. strcat()
28. Key Points to Remember
C does not have a separate built-in string data type.
Strings are stored using character arrays.
A C string ends with the null character '\0'.
%s is commonly used to display a string.
strlen() finds the length of a string.
strcpy() copies a string.
strcat() appends one string to another.
strcmp() compares two strings.
fgets() can be used to read a line containing spaces.
Always ensure that character arrays have enough space for their strings and the terminating null character.
Chapter Summary
Strings are an essential part of C programming because they allow programs to work with textual information. A C string is represented by a character array containing characters followed by a terminating null character.
By combining strings with loops, conditions, arrays, and standard library functions, programmers can perform useful operations such as searching, comparing, copying, joining, and modifying text.
A strong understanding of strings provides an important foundation for learning more advanced C programming concepts.
Next Chapter
Chapter 8 – Functions in C Language
In the next chapter, you will learn how to divide a large program into smaller, reusable blocks using functions.