Understanding Strings in C: A Complete Guide for Beginners

What is a String?

A string is a sequence of characters stored together. Think of a string as a chain of letters, digits, or symbols that form words or sentences.

In C, strings are stored as arrays of characters (char type), but with a special ending called the null character '\0' which marks where the string finishes.

How to Use Strings in C? Step by Step

  1. Declare a string: Use an array of characters.
  2. char name[10];  // Declares a string with space for 9 characters + null terminator
  3. Initialize a string: You can assign values while declaring.
  4. char greeting[] = "Hello";  // Automatically adds '\0' at the end
  5. Input a string: Use scanf or fgets to get user input.
  6. scanf("%s", name);  // Reads a word (stops at space)
  7. Access characters: You can use indexes like arrays.
  8. printf("%c\n", greeting[1]);  // Prints 'e'
  9. Print the whole string:
  10. printf("%s\n", greeting);  // Prints Hello

Important Concepts About Strings

Common Mistakes to Avoid When Using Strings

1. Forgetting the Null Terminator:
If your string does not have '\0' at the end, functions like printf won’t know where to stop and may print garbage.
Always make sure there’s enough space for '\0' when declaring or copying strings.
2. Using scanf("%s", ...) Without Size Limit:
It can cause buffer overflow if user inputs more characters than the array size.
Use scanf("%9s", name); if the array size is 10 to leave space for '\0'.
3. Trying to Change String Literals:
Strings declared as char *str = "Hello"; are stored in read-only memory.
Changing them causes undefined behavior.
Use character arrays if you want to modify strings.
4. Not Using String Library Functions:
C provides useful functions like strlen(), strcpy(), strcmp() in string.h to work with strings safely.
Avoid writing your own from scratch unless practicing.

Examples for Practice

Example 1: Declare and print a string

char name[] = "Rohan";
printf("Name: %s\n", name);

Example 2: Change characters in a string

name[0] = 'S';  // Changes "Rohan" to "Sohan"
printf("Updated Name: %s\n", name);

Example 3: Reading a string safely

char input[20];
printf("Enter your name: ");
scanf("%19s", input);  // Reads a word with max 19 chars + '\0'
printf("Hello, %s!\n", input);

Example 4: Using string functions

#include <string.h>
char str1[20] = "Hello";
char str2[20];
strcpy(str2, str1);  // Copies str1 into str2
printf("Copied string: %s\n", str2);
printf("Length: %lu\n", strlen(str2));

Summary

Further Learning

For more detailed explanations and examples, visit: