🔤 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 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.38 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?