Back to C Programming
2026-07-135 min read

Strings in C

Learn Strings in C step by step with clear examples and exercises.

Why This Matters

Strings are a fundamental data structure in programming, and understanding them is crucial for anyone looking to become proficient in C. Strings are used extensively in various applications such as web development, system programming, and even artificial intelligence. In this lesson, we will look closely at strings in C, exploring their definition, manipulation, formatting, comparison, concatenation, and common mistakes that developers often encounter when working with them.

The Importance of Strings

  • Strings allow us to store and manipulate text data, which is essential for creating user interfaces, parsing files, and communicating with other systems.
  • Understanding strings in C is a stepping stone towards mastering more complex programming tasks.

Prerequisites

Before diving into strings in C, it's essential to have a solid understanding of the following concepts:

  • Variables and data types (int, float, etc.)
  • Arrays
  • Pointers
  • Basic input/output using printf() and scanf()
  • File I/O (using functions like fopen(), fclose(), fgets(), and fprintf())

Core Concept

In C, strings are essentially arrays of characters terminated by a null character ('\0'). While we can define strings as pointers to an array of characters, it's more common to define them as local character arrays.

String Representation in Memory

  • A string is stored in memory as a contiguous block of characters, ending with a null character ('\0') that marks the end of the string.
  • This null character allows C to distinguish between a string and an array of individual characters.

Defining Strings

We can define a string using either pointer notation or local array notation:

Pointer Notation

const char * name = "John Smith";

This method creates a string that we can only use for reading. The const keyword ensures that the string cannot be modified.

Local Array Notation

char name[] = "John Smith";

This notation is used to define a string that can be manipulated. The empty brackets [] tell the compiler to calculate the size of the array automatically, which is one more than the length of the string (including the null character).

String Formatting with printf()

We can use the printf() function to format a string along with other strings and variables:

char name[] = "John Smith";
int age = 27;
printf("%s is %d years old.\n", name, age);

This will output 'John Smith is 27 years old.'

String Length

The strlen() function can be used to determine the length of a string:

char name[] = "Nikhil";
printf("%d\n", strlen(name));

This will output '5'

String Comparison

We can compare two strings using the strcmp() function. The function returns 0 if the strings are equal, and a non-zero value if they are different:

char name1[] = "John";
char name2[] = "Jane";
if (strcmp(name1, name2) == 0) {
printf("Hello, John!\n");
} else {
printf("You are not John. Go away.\n");
}

String Concatenation

We can concatenate two strings using the strncat() function:

char dest[20] = "Hello";
char src[20] = "World";
strncat(dest, src, 3);
printf("%s\n", dest); // Output: HelloWr
strncat(dest, src, 20);
printf("%s\n", dest); // Output: HelloWorld

Safe String Concatenation with strncpy() and strlen()

  • To avoid common errors such as buffer overflows when concatenating strings, it's recommended to use strncpy() along with strlen().
  • This approach ensures that the destination string has enough space to accommodate the source string and the null character.

Worked Example

Let's create a simple program that takes a user's first and last name as input, concatenates them, and outputs the full name.

#include <stdio.h>
#include <string.h>

int main() {
char first_name[20];
char last_name[20];
char full_name[40]; // Enough space for both names and the null character

printf("Enter your first name: ");
scanf("%s", first_name);

printf("Enter your last name: ");
scanf("%s", last_name);

// Copy the first name into the full name, ensuring there's enough space.
strncpy(full_name, first_name, sizeof(full_name) - strlen(last_name) - 1);

// Add a space and copy the last name into the full name.
strncat(full_name, " ", sizeof(full_name) - strlen(full_name) - 1);
strncpy(full_name + strlen(full_name), last_name, sizeof(full_name) - strlen(full_name) - 1);

printf("Your full name is: %s\n", full_name);

return 0;
}

Common Mistakes

  1. Forgetting to include the null character at the end of a string when using pointer notation.
  2. Trying to modify a string defined with pointer notation (since it's const char *).
  3. Not accounting for the null character when concatenating strings or determining their length.
  4. Using the unsafe strcmp() function instead of strncmp().
  5. Forgetting to include the necessary header files (` and `).
  6. Not checking for buffer overflow when concatenating strings.
  7. Not handling input errors correctly when using scanf().

Practice Questions

  1. Write a program that takes a user's name and age as input, formats them, and outputs "Hello [Name], you are [Age] years old!"
  2. Write a program that compares two strings entered by the user and determines whether they are equal or not.
  3. Write a program that concatenates three strings entered by the user (separated by spaces) and outputs the result.
  4. Write a program that reverses a given string using functions like strlen(), strncpy(), and strncat().
  5. Write a program that checks whether a given string is a palindrome or not.
  6. Write a program that counts the number of occurrences of a specific character in a given string.
  7. Write a program that removes all duplicate characters from a given string and sorts them alphabetically.
  8. Write a program that reads a file line by line, counts the number of words in each line, and calculates the average number of words per line in the file.
  9. Write a program that replaces all occurrences of a specific substring with another substring in a given string.
  10. Write a program that finds the longest common subsequence between two strings.

FAQ

A: We add one because the null character ('\0') is included as part of the string, which is not counted in the length.

Q: What's the difference between const char * and char [] for defining strings in C?

A: const char * creates a read-only string, while char [] creates a modifiable string.

Q: Why is it important to use functions like strlen() and strncat() when working with strings in C?

A: These functions help manage the memory used by strings efficiently and avoid common errors such as buffer overflows.

Q: What's the difference between strcmp() and strncmp()?

A: strcmp() compares two strings until it finds a null character, while strncmp() compares a maximum number of characters specified by the user.

Q: Why is it safer to use strncpy() instead of strcpy() when concatenating strings in C?

A: strncpy() ensures that the destination string has enough space for the source string and the null character, preventing buffer overflows.

Q: What's the difference between a palindrome and a symmetric word?

A: A palindrome is a word or phrase that reads the same backward as forward, ignoring spaces, punctuation, and case. A symmetric word is a word that looks the same when rotated 180 degrees, including spaces and punctuation.