Strings in C: An In-depth Introduction to Character Arrays

C Programming @ Freshers.in

Strings are a fundamental part of many C programs, allowing you to work with textual data. In this article, we will provide a comprehensive introduction to strings in C, covering what strings are, how to declare them, manipulate them, and provide practical examples with code and output.

What Are Strings?

In C, a string is an array of characters that represent textual data. Each character in a string is stored in a consecutive memory location, terminated by a null character ('\0'). Strings are typically used for storing and manipulating words, sentences, or any sequence of characters.

Declaring Strings

There are two common ways to declare strings in C:

  1. As Character Arrays: You can declare a string as an array of characters, like this:
char name[10]; // Declares a character array to store a name with a maximum of 10 characters
  1. Using String Literal: You can declare a string using a string literal, which is enclosed in double quotes:
char greeting[] = "Hello, World!";

Manipulating Strings

C provides a wide range of functions in the <string.h> library to manipulate strings. Here are some common operations:

  • Getting Length: You can use the strlen function to get the length of a string.
#include <stdio.h>
#include <string.h>
int main() {
    char greeting[] = "Hello, World!";
    int length = strlen(greeting);
    printf("Length of the string: %d\n", length);
    return 0;
}

Concatenation: You can use the strcat function to concatenate two strings.

#include <stdio.h>
#include <string.h>
int main() {
    char greeting[] = "Hello, ";
    char name[] = "Alice";
    strcat(greeting, name);
    printf("Greeting: %s\n", greeting);
    return 0;
}

Comparison: You can use functions like strcmp to compare two strings.

#include <stdio.h>
#include <string.h>
int main() {
    char str1[] = "apple";
    char str2[] = "banana";
    int result = strcmp(str1, str2);
    if (result < 0) {
        printf("%s comes before %s\n", str1, str2);
    } else if (result > 0) {
        printf("%s comes after %s\n", str1, str2);
    } else {
        printf("%s and %s are the same\n", str1, str2);
    }
    return 0;
}

Example: Reversing a String

Let’s look at a practical example where we reverse a string.

#include <stdio.h>
#include <string.h>
void reverseString(char str[]) {
    int length = strlen(str);
    for (int i = 0; i < length / 2; i++) {
        char temp = str[i];
        str[i] = str[length - i - 1];
        str[length - i - 1] = temp;
    }
}
int main() {
    char text[] = "Hello, World!";
    reverseString(text);
    printf("Reversed: %s\n", text);
    return 0;
}

In this example, we declare a string text, and then we use a custom function reverseString to reverse it. The output of this program will be:

Reversed: !dlroW ,olleH
Author: user