🔤 11. Strings
11.1 What Is a String?
C does not have a separate built-in string data type. A string is a sequence of characters stored in a character array and terminated by the null character \0.
"HELLO" Index: 0 1 2 3 4 5 Value: H E L L O \0
\0.11.2 Character vs String
Character
'A' is one character.
String
"A" is a string containing 'A' and '\0'.
Single quotes represent character constants; double quotes represent string literals.
11.3 Character Array — The Foundation
Strings are stored in arrays of char.
char name[20];The array must have enough space for all characters plus one byte for \0.
11.4 String Initialization
char a[] = "CodeBhavya";
char b[6] = "Hello";The compiler automatically adds \0 when a string literal initializes a character array with sufficient space.
char a[] = "Hello"; needs 6 elements, not 5.11.5 String Size and the Null Character
For "Hello", there are 5 visible characters but 6 stored characters including \0.
H e l l o \0
0 1 2 3 4 5strlen() counts characters before \0; sizeof measures the size of the array object when applied directly to an array.
11.6 Printing a String
char name[] = "Bhavya";
printf("%s", name);The %s conversion expects a pointer to a null-terminated character sequence and prints until \0.
11.7 Accessing Individual Characters
char word[] = "HELLO";
printf("%c", word[1]);Output: E. String characters are accessed using the same zero-based indexing rule as arrays.
11.8 Traversing a String
A common pattern is to continue until the null character is reached.
for (int i = 0; text[i] != '\0'; i++)
{
printf("%c", text[i]);
}Start → read text[i] → is it \0?
↓ No
process
↓
i++ ───→ repeat
↓ Yes
stop11.9 Reading a Single Word using scanf()
char name[50];
scanf("%49s", name);%s with scanf reads a word and stops at whitespace. A width such as %49s limits input and helps prevent writing beyond the array.
11.10 Reading a Line using fgets()
char text[100];
fgets(text, sizeof text, stdin);fgets() can read spaces and is generally the better choice when the input is a complete line. It may keep the newline character if it fits.
fgets() the actual buffer size using sizeof text.11.11 String Library Functions
The standard header <string.h> provides commonly used string functions.
Length
strlen()Copy
strcpy()Join
strcat()Compare
strcmp()11.12 strlen()
size_t n = strlen(text);strlen() returns the number of characters before \0. It does not count the null character.
11.13 strcpy()
char dest[20];
strcpy(dest, source);strcpy() copies the source string including its terminating \0. The destination must have enough capacity.
strcpy does not automatically resize the destination array.11.14 strcat()
char full[50] = "Code";
strcat(full, "Bhavya");strcat() appends the second string to the first. The destination must have enough unused space for the result and its terminating \0.
11.15 strcmp()
if (strcmp(a, b) == 0)
printf("Equal");strcmp() compares two strings lexicographically. Its result is 0 when the strings are equal, negative when the first compares smaller, and positive when it compares larger.
11.16 Find String Length Without strlen()
int len = 0;
while (text[len] != '\0')
len++;This reinforces the fundamental relationship: string processing = character traversal + a stopping condition at \0.
11.17 Count Vowels
Traverse the string and test each character against a, e, i, o, u in either case.
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')For case-insensitive processing, handle uppercase characters too or normalize the character first.
11.18 Count Consonants
A practical definition for beginner problems is: an alphabetic character that is not a vowel. Check that the character is a letter before classifying it as a consonant.
11.19 Count Digits in a String
Use the character range check c >= '0' && c <= '9'.
'0' ≤ c ≤ '9'11.20 Count Spaces and Whitespace
A literal space is different from all whitespace characters. If the problem asks specifically for spaces, test c == ' '. For broader whitespace handling, the ctype.h function isspace() can be used.
11.21 Convert Lowercase to Uppercase
For controlled ASCII-based examples, lowercase letters can be converted by changing their character code. Prefer the standard toupper() function from <ctype.h> for general character classification/conversion.
text[i] = (char)toupper((unsigned char)text[i]);11.22 Convert Uppercase to Lowercase
text[i] = (char)tolower((unsigned char)text[i]);When using ctype.h conversion functions, passing an unsigned char value cast to int avoids problems with negative plain-char values.
11.23 Reverse a String
Use two indexes: one at the beginning and one at the last character. Swap them and move inward.
left = 0;
right = strlen(text) - 1;
while (left < right)
{
char temp = text[left];
text[left] = text[right];
text[right] = temp;
left++;
right--;
}LEFT → C O D E ← RIGHT
swap → move inward → swap → ...11.24 Palindrome String
A palindrome reads the same forward and backward. Compare matching characters from both ends.
left == right? → continue
left != right? → not a palindromeTypical examples: madam, level.
11.25 Compare Two Strings Without strcmp()
Traverse both strings together. They are equal only when every corresponding character matches and both strings reach \0 together.
while (a[i] != '\0' && b[i] != '\0' && a[i] == b[i])
i++;11.26 Copy String Without strcpy()
int i = 0;
while (source[i] != '\0')
{
dest[i] = source[i];
i++;
}
dest[i] = '\0';\0 must also be copied.11.27 Concatenate Without strcat()
First move to the end of the destination string, then copy characters from the source and finally append \0.
int i = 0, j = 0;
while (dest[i] != '\0') i++;
while (source[j] != '\0')
dest[i++] = source[j++];
dest[i] = '\0';11.28 Frequency of a Character
Scan the string and increment a counter whenever the target character is found.
if (text[i] == target)
count++;This simple pattern appears frequently in placement problems.
11.29 Remove Spaces from a String
Use separate read and write positions. Copy only characters that should remain.
int write = 0;
for (int read = 0; text[read] != '\0'; read++)
if (text[read] != ' ')
text[write++] = text[read];
text[write] = '\0';read index → inspect → keep? → write index → next character
11.30 Count Words in a Sentence
A common beginner approach is to detect transitions from whitespace to a non-whitespace character. Handle leading, trailing, and repeated spaces carefully.
11.31 Check Whether a String Contains Only Alphabets
Traverse every character and verify that it is an alphabetic character. The isalpha() function from <ctype.h> is useful.
if (!isalpha((unsigned char)text[i]))
valid = 0;11.32 First Non-Repeating Character
This is a common placement pattern:
Step 1 → Count frequency of every character Step 2 → Scan the original string left to right Step 3 → Find the first character with frequency 1 Step 4 → Report it
The key idea is to preserve the original order during the second scan.
11.33 Array of Strings
Multiple strings can be stored in a two-dimensional character array.
char names[5][100];Here each row can hold one null-terminated string of up to 99 characters plus \0.
11.34 scanf() vs fgets() — Choose the Input Method
| Method | Typical use | Whitespace |
|---|---|---|
scanf("%s", ...) | Single word | Stops at whitespace |
fgets() | Complete line | Can read spaces |
For a line-oriented problem, fgets() is usually the clearer choice. If it stores the newline, remove it when the problem requires a clean string.
11.35 Why is \0 Important?
The null character tells string functions where the string ends. Without it, a function such as printf("%s", text) may continue reading memory beyond the intended characters until a zero byte happens to be found.
H E L L O \0 | unrelated memory... ←---- string ----→
char text[100] can have capacity 99 visible characters plus \0, but its current string may be much shorter.11.36 Common String Mistakes
- Forgetting space for
\0. - Using
==to compare string contents. - Using
scanf("%s", text)when the input contains spaces. - Calling
strcpyorstrcatwithout enough destination capacity. - Forgetting that
fgets()may keep the newline. - Reading or writing outside the array bounds.
- Forgetting to terminate a manually constructed string with
\0. - Confusing
strlen(text)withsizeof(text).
\0 is.11.37 Finding Substrings and Removing the fgets Newline
Useful functions from <string.h> include strchr (find a character), strstr (find a substring) and strcspn (find the length of an initial span not containing specified characters). When fgets reads a newline and there is room in the buffer, that newline may be stored; remove it before comparing names or sentences.
Complete C program:
#include <stdio.h>
#include <string.h>
int main(void)
{
char text[64] = "Welcome to C\n";
text[strcspn(text, "\n")] = '\0';
printf("Clean text: %s\n", text);
printf("Contains C: %s\n",
strstr(text, "C") != NULL ? "yes" : "no");
return 0;
}
Expected output:
Clean text: Welcome to C
Contains C: yes
Step-by-step explanation:
- strcspn finds the first newline or the terminating null character.
- Assigning a null character removes the newline when present.
- strstr returns a pointer to the first occurrence or NULL when no match is found.
11.38 Tokenizing Text with strtok — and Its Tradeoffs
strtok splits a writable string into tokens using delimiter characters. The first call supplies the string, and later calls supply NULL. It modifies the original buffer and uses internal state, so avoid it when you must preserve the input or parse different streams interleaved.
Complete C program:
#include <stdio.h>
#include <string.h>
int main(void)
{
char names[] = "C,Python,Java";
char *token = strtok(names, ",");
while (token != NULL) {
puts(token);
token = strtok(NULL, ",");
}
return 0;
}
Expected output:
C
Python
Java
Step-by-step explanation:
- The first strtok call finds C and replaces the first comma with a null character.
- The following calls continue from the saved position.
- The loop ends when no further token exists.
11.39 Quick Revision
📌 Strings are stored as character arrays.
📌 Strings end with \0.
📌 %s is used for string output.
📌 strlen() → length.
📌 strcpy() → copy.
📌 strcat() → concatenate.
📌 strcmp() → compare.
📌 fgets() can read spaces.
🎬 Strings — Character Traversal
Follow how C traverses a character array until the null terminator \0.
🎬 String Traversal Visualizer
The currently visited character becomes active as the traversal moves toward \0.
🔎 Program Tracing — Strings
Trace character-by-character traversal while counting vowels in a string.
—
11.40 Quick MCQs
Select an answer first, then click Check Answer. A correct choice becomes green. If the answer is wrong, your choice becomes red and the correct option becomes green. The explanation appears below.
A C string ends with the null character ''.
%s is used with printf() to print a null-terminated string.
strlen() returns the number of characters before the terminating ''.
strcmp() compares two strings lexicographically.
strcat() appends one null-terminated string to another destination string with sufficient capacity.
fgets() can read a line including spaces, up to the supplied buffer limit.
11.41 🎯 Practice Problems
Strings become easy when you understand character arrays, , and traversal.
Use 💻 Solve It Yourself first,
open Hint only when needed,
and use Show Program after attempting the problem.
Problem 1: Read a complete line of text and print it.
Input: One line of text.
Output: Print the same line.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
#include <string.h>
int main()
{
char text[200];
fgets(text, sizeof(text), stdin);
text[strcspn(text, "\n")] = '\0';
printf("%s", text);
return 0;
}
Problem 2: Find the length of a string without using strlen().
Input: One line of text.
Output: Print the number of characters, excluding the newline and null terminator.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
char text[200];
int length = 0;
fgets(text, sizeof(text), stdin);
while (text[length] != '\0' && text[length] != '\n')
length++;
printf("%d", length);
return 0;
}
Problem 3: Count vowels in a string.
Input: One line of text.
Output: Print the vowel count.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
char text[200];
int count = 0;
fgets(text, sizeof(text), stdin);
for (int i = 0; text[i] != '\0'; i++)
{
char ch = text[i];
if (ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u' ||
ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U')
{
count++;
}
}
printf("%d", count);
return 0;
}
Problem 4: Count consonant letters in a string.
Input: One line of text.
Output: Print the consonant count.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
#include <ctype.h>
int main()
{
char text[200];
int count = 0;
fgets(text, sizeof(text), stdin);
for (int i = 0; text[i] != '\0'; i++)
{
char ch = (char)tolower((unsigned char)text[i]);
if (isalpha((unsigned char)ch) &&
!(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u'))
{
count++;
}
}
printf("%d", count);
return 0;
}
Problem 5: Count digit characters in a string.
Input: One line of text.
Output: Print the number of digit characters.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
#include <ctype.h>
int main()
{
char text[200];
int count = 0;
fgets(text, sizeof(text), stdin);
for (int i = 0; text[i] != '\0'; i++)
{
if (isdigit((unsigned char)text[i]))
count++;
}
printf("%d", count);
return 0;
}
Problem 6: Count space characters in a sentence.
Input: One line of text.
Output: Print the number of spaces.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
char text[200];
int count = 0;
fgets(text, sizeof(text), stdin);
for (int i = 0; text[i] != '\0'; i++)
{
if (text[i] == ' ')
count++;
}
printf("%d", count);
return 0;
}
Problem 7: Convert lowercase letters in a string to uppercase.
Input: One line of text.
Output: Print the converted string.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
#include <ctype.h>
int main()
{
char text[200];
fgets(text, sizeof(text), stdin);
for (int i = 0; text[i] != '\0'; i++)
text[i] = (char)toupper((unsigned char)text[i]);
printf("%s", text);
return 0;
}
Problem 8: Convert uppercase letters in a string to lowercase.
Input: One line of text.
Output: Print the converted string.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
#include <ctype.h>
int main()
{
char text[200];
fgets(text, sizeof(text), stdin);
for (int i = 0; text[i] != '\0'; i++)
text[i] = (char)tolower((unsigned char)text[i]);
printf("%s", text);
return 0;
}
Problem 9: Reverse a string and print the reversed result.
Input: One line of text.
Output: Print the characters in reverse order.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
#include <string.h>
int main()
{
char text[200];
fgets(text, sizeof(text), stdin);
text[strcspn(text, "\n")] = '\0';
int length = (int)strlen(text);
for (int i = length - 1; i >= 0; i--)
putchar(text[i]);
return 0;
}
Problem 10: Check whether a string is a palindrome.
Input: One word or line.
Output: Print "Palindrome" or "Not Palindrome".
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
#include <string.h>
int main()
{
char text[200];
int palindrome = 1;
fgets(text, sizeof(text), stdin);
text[strcspn(text, "\n")] = '\0';
int left = 0;
int right = (int)strlen(text) - 1;
while (left < right)
{
if (text[left] != text[right])
{
palindrome = 0;
break;
}
left++;
right--;
}
printf("%s", palindrome ? "Palindrome" : "Not Palindrome");
return 0;
}
Problem 11: Compare two strings without using strcmp().
Input: Two lines of text.
Output: Print "Equal", "First Smaller", or "First Greater".
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
#include <string.h>
int main()
{
char a[200], b[200];
int i = 0;
fgets(a, sizeof(a), stdin);
fgets(b, sizeof(b), stdin);
a[strcspn(a, "\n")] = '\0';
b[strcspn(b, "\n")] = '\0';
while (a[i] != '\0' && b[i] != '\0' && a[i] == b[i])
i++;
if (a[i] == b[i])
printf("Equal");
else if ((unsigned char)a[i] < (unsigned char)b[i])
printf("First Smaller");
else
printf("First Greater");
return 0;
}
Problem 12: Copy one string to another without using strcpy().
Input: One line of text.
Output: Print the copied string.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
#include <string.h>
int main()
{
char source[200];
char destination[200];
int i = 0;
fgets(source, sizeof(source), stdin);
source[strcspn(source, "\n")] = '\0';
do
{
destination[i] = source[i];
}
while (source[i++] != '\0');
printf("%s", destination);
return 0;
}
Problem 13: Concatenate two strings without using strcat().
Input: Two lines of text.
Output: Print the concatenated string.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
#include <string.h>
int main()
{
char a[400], b[200];
int i = 0;
int j = 0;
fgets(a, sizeof(a), stdin);
fgets(b, sizeof(b), stdin);
a[strcspn(a, "\n")] = '\0';
b[strcspn(b, "\n")] = '\0';
while (a[i] != '\0')
i++;
while (b[j] != '\0')
a[i++] = b[j++];
a[i] = '\0';
printf("%s", a);
return 0;
}
Problem 14: Count how many times a given character appears in a string.
Input: First line: text. Second line: one character.
Output: Print the frequency.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
#include <string.h>
int main()
{
char text[200];
char target;
int count = 0;
fgets(text, sizeof(text), stdin);
text[strcspn(text, "\n")] = '\0';
scanf("%c", &target);
for (int i = 0; text[i] != '\0'; i++)
{
if (text[i] == target)
count++;
}
printf("%d", count);
return 0;
}
Problem 15: Remove all space characters from a string.
Input: One line of text.
Output: Print the string without spaces.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
#include <string.h>
int main()
{
char text[200];
int write = 0;
fgets(text, sizeof(text), stdin);
text[strcspn(text, "\n")] = '\0';
for (int read = 0; text[read] != '\0'; read++)
{
if (text[read] != ' ')
text[write++] = text[read];
}
text[write] = '\0';
printf("%s", text);
return 0;
}
Problem 16: Count the number of words in a sentence.
Input: One line of text.
Output: Print the word count.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
#include <ctype.h>
int main()
{
char text[300];
int words = 0;
int inWord = 0;
fgets(text, sizeof(text), stdin);
for (int i = 0; text[i] != '\0'; i++)
{
if (isspace((unsigned char)text[i]))
{
inWord = 0;
}
else if (!inWord)
{
words++;
inWord = 1;
}
}
printf("%d", words);
return 0;
}
Problem 17: Check whether a string contains only alphabetic characters.
Input: One line of text.
Output: Print "Only Alphabets" or "Not Only Alphabets".
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main()
{
char text[200];
int only = 1;
fgets(text, sizeof(text), stdin);
text[strcspn(text, "\n")] = '\0';
if (text[0] == '\0')
only = 0;
for (int i = 0; text[i] != '\0'; i++)
{
if (!isalpha((unsigned char)text[i]))
{
only = 0;
break;
}
}
printf("%s", only ? "Only Alphabets" : "Not Only Alphabets");
return 0;
}
Problem 18: Find the first character that occurs exactly once.
Input: One line of text.
Output: Print the first non-repeating character, or None.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
#include <string.h>
int main()
{
char text[200];
int freq[256] = {0};
fgets(text, sizeof(text), stdin);
text[strcspn(text, "\n")] = '\0';
for (int i = 0; text[i] != '\0'; i++)
freq[(unsigned char)text[i]]++;
for (int i = 0; text[i] != '\0'; i++)
{
if (freq[(unsigned char)text[i]] == 1)
{
printf("%c", text[i]);
return 0;
}
}
printf("None");
return 0;
}
Problem 19: Find the first character whose total frequency is greater than one.
Input: One line of text.
Output: Print the first repeating character in original order, or None.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
#include <string.h>
int main()
{
char text[200];
int freq[256] = {0};
fgets(text, sizeof(text), stdin);
text[strcspn(text, "\n")] = '\0';
for (int i = 0; text[i] != '\0'; i++)
freq[(unsigned char)text[i]]++;
for (int i = 0; text[i] != '\0'; i++)
{
if (freq[(unsigned char)text[i]] > 1)
{
printf("%c", text[i]);
return 0;
}
}
printf("None");
return 0;
}
Problem 20: Store five student names in a two-dimensional character array and print them.
Input: Exactly five lines, one student name per line.
Output: Print the five names, one per line.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
#include <string.h>
int main()
{
char names[5][100];
for (int i = 0; i < 5; i++)
{
fgets(names[i], sizeof(names[i]), stdin);
names[i][strcspn(names[i], "\n")] = '\0';
}
for (int i = 0; i < 5; i++)
{
printf("%s", names[i]);
if (i < 4)
printf("\n");
}
return 0;
}
11.42 Key Takeaway
String → Character Array → Loop → Process
Example: finding vowels follows this process:
🎤 Strings — Interview Questions
💡 Strings — Placement Tips
- Always remember that a valid C string requires a terminating \0.
- When reading sentences, prefer fgets() over
scanf("%s"). - For manual string algorithms, trace indices and characters just like array problems.
- For palindrome and reverse problems, think in terms of left and right positions.
- For frequency problems, a small frequency table indexed by
unsigned charvalues is often useful. - Before copying or concatenating strings, always ensure the destination buffer has enough capacity.
✍️ Strings — Extra Practice Questions
- Find the longest word in a sentence.
- Remove duplicate characters while preserving the first occurrence.
- Check whether two strings are anagrams.
- Count uppercase letters, lowercase letters, digits, spaces, and special characters separately.
- Replace every occurrence of one character with another.
- Find the most frequent character in a string.