Paramclasses Academy - Blog

Tutorials Details

←
Post 11 of 15
→

What is Strings in C Programming ?

What is Strings in C Programming ?

October 14, 2026

1. Introduction to Strings

In C programming, a string is a sequence of characters used to represent text, such as a person's name, city, email address, or message.

C does not have a built-in string data type. Instead, strings are typically stored in character arrays (char arrays) and terminated by a special null character, '\0'.

Example:

char name[] = "Param";

This string contains the characters P, a, r, a, m, followed by the terminating null character '\0'.

In this module, you will learn:

  • String declaration and initialization

  • String input and output

  • fgets() and puts()

  • Common string functions: strlen(), strcpy(), strcat(), and strcmp()

  • Processing strings using loops

  • Counting vowels, reversing strings, and checking palindromes

  • Common mistakes, practical programs, and interview questions

2. What Is a String in C?

A C string is a sequence of characters that ends with the null character '\0'.

Syntax

char string_name[size];

Example:

char name[20];

This declares a character array with a capacity of 20 characters. When used as a C string, one position must be reserved for '\0', allowing up to 19 ordinary characters.

String memory representation

Consider the following code:

char word[] = "CAT";

The array contains:

C

Index 0

A

Index 1

T

Index 2

\0

Index 3

The null character marks the end of the string and has a value of zero.

Important points:

  • Strings are commonly stored in character arrays.

  • Array indexing starts at 0.

  • The null character marks the end of a C string.

  • A character array is not automatically a valid string unless it contains a terminating null character.

3. String Declaration and Initialization

Method 1: Initialize during declaration

char name[] = "Param";

The compiler determines the required array size, including the null terminator.

Method 2: Declare a fixed-size array

char city[20] = "Raipur";

The array has room for 20 characters, including the null terminator.

Method 3: Initialize character by character

char word[] = {'H', 'e', 'l', 'l', 'o', '\0'};

Here, '\0' is explicitly included to terminate the string.

Method 4: Use a pointer to a string literal

const char *message = "Hello";

This creates a pointer to a string literal. The literal must not be modified; using const char * communicates that restriction clearly.

Important: A modifiable character array and a string literal are different. You can modify the elements of an appropriately declared character array, but modifying a string literal causes undefined behavior.

4. Displaying Strings with printf() and puts()

The %s format specifier displays a string.

Example:

#include <stdio.h>

int main(void)
{
    char name[] = "Param";

    printf("My name is %s\n", name);

    return 0;
}

Output:

My name is Param

Using puts()

#include <stdio.h>

int main(void)
{
    char message[] = "Welcome to C Programming";

    puts(message);

    return 0;
}

Output:

Welcome to C Programming

The puts() function automatically adds a newline after displaying the string.

5. Taking String Input from the User

Method 1: Using scanf() for a single word

#include <stdio.h>

int main(void)
{
    char name[30];

    printf("Enter your name: ");

    if (scanf("%29s", name) != 1)
    {
        printf("Input error.\n");
        return 1;
    }

    printf("Hello, %s!\n", name);

    return 0;
}

Example output:

Enter your name: Rahul
Hello, Rahul!

Why use %29s instead of %s?

The array can hold 30 characters, so %29s limits the input to 29 characters and leaves room for the terminating '\0'.

Note that %s stops reading at whitespace. If the user enters Rahul Kumar, only Rahul is read.

Method 2: Using fgets() for a complete line

Use fgets() when you need to read spaces as part of the input.

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

int main(void)
{
    char fullName[50];

    printf("Enter your full name: ");

    if (fgets(fullName, sizeof fullName, stdin) == NULL)
    {
        printf("Input error.\n");
        return 1;
    }

    fullName[strcspn(fullName, "\n")] = '\0';

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

    return 0;
}

Example output:

Enter your full name: Rahul Kumar
Your name is: Rahul Kumar

Explanation:

  • fgets() reads a line, including spaces.

  • sizeof fullName provides the buffer capacity.

  • strcspn() finds the position of the newline, if present.

  • The newline is replaced with '\0'.

fgets() limits how much input it reads, so programs that accept longer input should also consider how to handle truncated lines.

6. Finding String Length with strlen()

The strlen() function returns the number of characters in a string, excluding the terminating '\0'.

It is declared in the <string.h> header.

Syntax

strlen(string_name);

Example:

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

int main(void)
{
    char name[] = "Param";

    printf("Length: %zu\n", strlen(name));

    return 0;
}

Output:

Length: 5

The %zu format specifier is used to print the size_t value returned by strlen().

7. Copying Strings with strcpy()

The strcpy() function copies a source string into a destination character array.

Syntax

strcpy(destination, source);

Example:

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

int main(void)
{
    char source[] = "Hello";
    char destination[20];

    strcpy(destination, source);

    printf("Copied string: %s\n", destination);

    return 0;
}

Output:

Copied string: Hello

Important: The destination must have enough space for all source characters and the terminating null character. Otherwise, the operation can cause a buffer overflow and undefined behavior.

8. Joining Strings with strcat()

The strcat() function appends a source string to the end of a destination string.

Syntax

strcat(destination, source);

Example:

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

int main(void)
{
    char first[30] = "Hello ";
    char second[] = "World";

    strcat(first, second);

    printf("%s\n", first);

    return 0;
}

Output:

Hello World

The destination array has enough capacity to hold the combined string and its terminating null character.

9. Comparing Strings with strcmp()

The strcmp() function compares two strings lexicographically.

Syntax

strcmp(string1, string2);

Return values:

  • 0: Both strings are equal.

  • A negative value: The first string is lexicographically smaller.

  • A positive value: The first string is lexicographically greater.

Example:

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

int main(void)
{
    char first[] = "apple";
    char second[] = "apple";

    if (strcmp(first, second) == 0)
    {
        printf("Strings are equal.\n");
    }
    else
    {
        printf("Strings are different.\n");
    }

    return 0;
}

Output:

Strings are equal.

Common mistake: Do not use first == second to compare string contents. Use strcmp() to compare the characters in two strings.

10. Important String Functions

Function

Purpose

strlen()

Returns the string length

strcpy()

Copies a source string

strcat()

Appends one string to another

strcmp()

Compares two strings

strchr()

Searches for a character

strstr()

Searches for a substring

fgets()

Reads a line into a buffer

puts()

Displays a string followed by a newline

The commonly used string functions are declared in <string.h>, while fgets() and puts() are declared in <stdio.h>.

11. Processing a String Using a Loop

You can access each character of a string using a loop that continues until it reaches '\0'.

Example:

#include <stdio.h>

int main(void)
{
    char word[] = "HELLO";
    int i;

    for (i = 0; word[i] != '\0'; i++)
    {
        printf("%c\n", word[i]);
    }

    return 0;
}

Output:

H
E
L
L
O

The %c format specifier prints one character at a time, and the loop stops when it reaches the null terminator.

12. Practical Program: Count Vowels

This program counts vowels in a string, including both uppercase and lowercase vowels.

#include <stdio.h>

int main(void)
{
    char text[100];
    int i;
    int vowels = 0;

    printf("Enter a line: ");

    if (fgets(text, sizeof text, stdin) == NULL)
    {
        printf("Input error.\n");
        return 1;
    }

    for (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')
        {
            vowels++;
        }
    }

    printf("Number of vowels: %d\n", vowels);

    return 0;
}

Example output:

Enter a line: Hello World
Number of vowels: 3

The program checks every character and increases the vowel counter whenever it finds a, e, i, o, or u, regardless of case.

13. Practical Program: Reverse a String

This program prints a string in reverse order without modifying the original string.

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

int main(void)
{
    char text[] = "PARAM";
    size_t length = strlen(text);
    size_t i;

    printf("Reverse: ");

    for (i = length; i > 0; i--)
    {
        printf("%c", text[i - 1]);
    }

    printf("\n");

    return 0;
}

Output:

Reverse: MARAP

The loop starts at the last character and prints each character until it reaches the first.

14. Practical Program: Check a Palindrome

A palindrome is a word that reads the same forward and backward, such as MADAM.

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

int main(void)
{
    char text[] = "MADAM";
    size_t length = strlen(text);
    size_t i;
    int palindrome = 1;

    for (i = 0; i < length / 2; i++)
    {
        if (text[i] != text[length - 1 - i])
        {
            palindrome = 0;
            break;
        }
    }

    if (palindrome)
    {
        printf("Palindrome\n");
    }
    else
    {
        printf("Not a palindrome\n");
    }

    return 0;
}

Output:

Palindrome

This example is case-sensitive and does not ignore spaces or punctuation; a more advanced palindrome checker would need to normalize the input first.

15. Common Mistakes in Strings

Mistake 1: Not reserving space for the null terminator

char word[6] = "Hello";

This is correct because the array can hold five letters and '\0'.

Mistake 2: Expecting scanf("%s", ...) to read a full name

%s stops at whitespace, so use fgets() when you need a complete line.

Mistake 3: Using strcpy() with a small destination

The destination must have enough space for the source string and its null terminator.

Mistake 4: Comparing strings with ==

Use strcmp() to compare string contents.

Mistake 5: Reading an uninitialized character array

String functions require valid null-terminated strings; initialize or populate the array before using these functions.

16. Practical Programs for Practice

  1. Input and display a first name.

  2. Read a full name using fgets().

  3. Find a string's length using strlen().

  4. Count vowels and consonants.

  5. Print a string in reverse order.

  6. Write a palindrome checker.

  7. Copy a string using strcpy().

  8. Combine first and last names using strcat().

  9. Compare two strings using strcmp().

  10. Search for a character in a string.

17. Interview Questions

Q1. What is a string in C?

A string is a null-terminated sequence of characters, commonly stored in a char array.

Q2. What is the purpose of '\0'?

It marks the end of a C string.

Q3. What is the difference between strlen() and sizeof?

strlen() counts characters before the null terminator, while sizeof returns the size in bytes of an object or array.

Q4. Why is fgets() useful?

It can read spaces as part of a line and lets you specify the maximum number of characters to read.

Q5. What does strcmp() return when two strings are equal?

It returns 0.

Q6. Can you modify a string literal in C?

No. Attempting to modify a string literal causes undefined behavior; use a modifiable character array instead.

Q7. Which header file contains common string functions?

<string.h>.

18. Quick Revision

  • C has no built-in string data type.

  • Strings are commonly stored in character arrays.

  • '\0' marks the end of a C string.

  • %s is used to display strings with printf().

  • fgets() can read lines containing spaces.

  • strlen() measures length; strcpy() copies; strcat() appends; strcmp() compares.

  • Always check buffer capacity and null termination.

  • Avoid out-of-bounds access and unsafe string copying.

19. Homework

  1. Write the definition and syntax of a string in C.

  2. Write examples using strlen(), strcpy(), strcat(), and strcmp().

  3. Create a program that reads and displays a full name.

  4. Write a program to count vowels in a string.

  5. Write a program to print a string in reverse.

  6. Create a palindrome checker.

  7. Explain the difference between strlen() and sizeof in your own words.

Conclusion

In this module, you learned how to declare, initialize, input, display, and process strings in C, along with essential string functions and practical programs.

←
Post 11 of 15
→