🔤 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
Core rule: A C string is valid only when its characters are followed by \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.

Required size = number of visible characters + 1

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.

Do not confuse: 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   5

strlen() 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
                   stop

11.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.

Safe habit: give 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.

Important: 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'.

Digit condition: '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 palindrome

Typical 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';
Do not forget: the final \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.

Boundary idea: a word begins when a non-space character appears after the beginning of the string or after whitespace.

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

MethodTypical useWhitespace
scanf("%s", ...)Single wordStops at whitespace
fgets()Complete lineCan 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 ----→
Array size and string length are different: 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 strcpy or strcat without 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) with sizeof(text).
CodeBhavya Rule: Whenever you manipulate a string manually, always know three things: buffer capacity, current length, and where \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:

  1. strcspn finds the first newline or the terminating null character.
  2. Assigning a null character removes the newline when present.
  3. strstr returns a pointer to the first occurrence or NULL when no match is found.
Remember: Only pass null-terminated strings to string functions. strstr is case-sensitive and may match inside a longer word.

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:

  1. The first strtok call finds C and replaces the first comma with a null character.
  2. The following calls continue from the saved position.
  3. The loop ends when no further token exists.
Remember: Do not call strtok on a string literal; it writes into its input buffer. It also does not preserve empty fields.

11.39 Quick Revision

📌 C has no built-in string data type.

📌 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.
INTERACTIVE LEARNING

🎬 Strings — Character Traversal

Follow how C traverses a character array until the null terminator \0.

PROGRAM TRACING

🔎 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.

1. Which character terminates a C string?
2. Which format specifier is used to print a string?
3. Which function finds the length of a string?
4. Which function compares two strings?
5. Which function concatenates strings?
6. Which function can read a line containing spaces?
PRACTICE

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.

📈 Strings Practice Progress
Solved 0 / 20
Completed with Solution 0
Total Score 0 / 400
Completion 0%
A problem counts as Solved when all test cases pass without opening the full solution. Problems completed after viewing the official solution are tracked separately.
1. Read and Print a String

Problem 1: Read a complete line of text and print it.

Input: One line of text.

Output: Print the same line.

2. Length Without strlen()

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.

3. Count Vowels

Problem 3: Count vowels in a string.

Input: One line of text.

Output: Print the vowel count.

4. Count Consonants

Problem 4: Count consonant letters in a string.

Input: One line of text.

Output: Print the consonant count.

5. Count Digits in a String

Problem 5: Count digit characters in a string.

Input: One line of text.

Output: Print the number of digit characters.

6. Count Spaces

Problem 6: Count space characters in a sentence.

Input: One line of text.

Output: Print the number of spaces.

7. Lowercase to Uppercase

Problem 7: Convert lowercase letters in a string to uppercase.

Input: One line of text.

Output: Print the converted string.

8. Uppercase to Lowercase

Problem 8: Convert uppercase letters in a string to lowercase.

Input: One line of text.

Output: Print the converted string.

9. Reverse a String

Problem 9: Reverse a string and print the reversed result.

Input: One line of text.

Output: Print the characters in reverse order.

10. Palindrome String

Problem 10: Check whether a string is a palindrome.

Input: One word or line.

Output: Print "Palindrome" or "Not Palindrome".

11. Compare Without strcmp()

Problem 11: Compare two strings without using strcmp().

Input: Two lines of text.

Output: Print "Equal", "First Smaller", or "First Greater".

12. Copy Without strcpy()

Problem 12: Copy one string to another without using strcpy().

Input: One line of text.

Output: Print the copied string.

13. Concatenate Without strcat()

Problem 13: Concatenate two strings without using strcat().

Input: Two lines of text.

Output: Print the concatenated string.

14. Frequency of a Character

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.

15. Remove All Spaces

Problem 15: Remove all space characters from a string.

Input: One line of text.

Output: Print the string without spaces.

16. Count Words

Problem 16: Count the number of words in a sentence.

Input: One line of text.

Output: Print the word count.

17. Contains Only Alphabets

Problem 17: Check whether a string contains only alphabetic characters.

Input: One line of text.

Output: Print "Only Alphabets" or "Not Only Alphabets".

18. First Non-Repeating Character

Problem 18: Find the first character that occurs exactly once.

Input: One line of text.

Output: Print the first non-repeating character, or None.

19. First Repeating Character

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.

20. Store and Print 5 Student Names

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.

11.42 Key Takeaway

🎯 Remember the basic string pattern:

String → Character Array → Loop → Process

Example: finding vowels follows this process:
Step 1
Traverse Characters
↓
Step 2
Check Each Character
↓
Step 3
Update the Required Result
↓
Step 4
Print the Result
Mastering strings will make many coding-platform problems much easier.
INTERVIEW PREPARATION

🎤 Strings — Interview Questions

1. Why is the null character important in a C string?
2. What is the difference between a character and a string in C?
3. What is the difference between scanf("%s") and fgets()?
4. Does strlen() count the terminating null character?
5. Why can strcpy() and strcat() be dangerous when the destination buffer is too small?
6. How does strcmp() report the comparison result?
7. Why are strings often processed with loops?
8. What is an array of strings in C?
PLACEMENT TIPS

💡 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 char values is often useful.
  • Before copying or concatenating strings, always ensure the destination buffer has enough capacity.
EXTRA PRACTICE

✍️ Strings — Extra Practice Questions

  1. Find the longest word in a sentence.
  2. Remove duplicate characters while preserving the first occurrence.
  3. Check whether two strings are anagrams.
  4. Count uppercase letters, lowercase letters, digits, spaces, and special characters separately.
  5. Replace every occurrence of one character with another.
  6. Find the most frequent character in a string.
← Previous Topic: Arrays Next Topic: Functions →