C Strings

Introduction

In the previous chapters, we explored arrays in C, including one-dimensional and multidimensional arrays. In this chapter, we will focus on strings. Strings are sequences of characters that are commonly used in programming to represent text. In C, strings are treated as arrays of characters and are terminated by a special character called the null character (\0).

What is a String?

A string in C is an array of characters terminated by the null character (\0). The null character marks the end of the string and is important for various string-handling functions to determine the length of the string.

Syntax

The basic syntax for declaring a string in C is as follows:

char string_name[array_size];
  • char: The type of elements stored in the array, which are characters.
  • string_name: The name of the string.
  • array_size: The maximum number of characters the string can hold, including the null character.

Example: Declaring and Initializing a String

Let’s look at a simple example to understand how to declare and initialize a string.

Example: Declaring and Initializing a String

#include <stdio.h>

int main() {
    // Declaring and initializing a string
    char greeting[6] = "Hello";

    // Accessing and printing the string
    printf("Greeting: %s\n", greeting);

    return 0; // Returning 0 to indicate successful execution
}

Output:

Greeting: Hello

In this example, we declared a string named greeting with a size of 6 characters, including the null character. We initialized it with the string "Hello".

Accessing String Elements

String elements can be accessed using their index, similar to how elements in an array are accessed.

Example: Accessing String Elements

#include <stdio.h>

int main() {
    char greeting[] = "Hello";

    // Accessing and printing each character of the string
    for (int i = 0; i < 5; i++) {
        printf("Character at index %d: %c\n", i, greeting[i]);
    }

    return 0; // Returning 0 to indicate successful execution
}

Output:

Character at index 0: H
Character at index 1: e
Character at index 2: l
Character at index 3: l
Character at index 4: o

String Functions

C provides several standard library functions for manipulating strings. Some of the most commonly used string functions are:

1. strlen: Calculate the Length of a String

The strlen function calculates the length of a string, excluding the null character.

Syntax:

size_t strlen(const char *str);

Example:

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

int main() {
    char greeting[] = "Hello";
    size_t length = strlen(greeting);

    printf("Length of the string: %zu\n", length);

    return 0; // Returning 0 to indicate successful execution
}

Output:

Length of the string: 5

2. strcpy: Copy a String

The strcpy function copies the content of one string to another.

Syntax:

char *strcpy(char *dest, const char *src);

Example:

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

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

    strcpy(destination, source);

    printf("Source: %s\n", source);
    printf("Destination: %s\n", destination);

    return 0; // Returning 0 to indicate successful execution
}

Output:

Source: Hello
Destination: Hello

3. strcat: Concatenate Two Strings

The strcat function concatenates (appends) one string to the end of another.

Syntax:

char *strcat(char *dest, const char *src);

Example:

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

int main() {
    char greeting[11] = "Hello";
    char name[] = "World";

    strcat(greeting, name);

    printf("Concatenated String: %s\n", greeting);

    return 0; // Returning 0 to indicate successful execution
}

Output:

Concatenated String: HelloWorld

4. strcmp: Compare Two Strings

The strcmp function compares two strings lexicographically.

Syntax:

int strcmp(const char *str1, const char *str2);

Example:

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

int main() {
    char string1[] = "Hello";
    char string2[] = "World";
    int result = strcmp(string1, string2);

    if (result == 0) {
        printf("The strings are equal.\n");
    } else if (result < 0) {
        printf("String1 is less than String2.\n");
    } else {
        printf("String1 is greater than String2.\n");
    }

    return 0; // Returning 0 to indicate successful execution
}

Output:

String1 is less than String2.

Simple C Programs to Demonstrate Strings

Program 1: Reverse a String

Example:

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

int main() {
    char str[] = "Hello";
    int length = strlen(str);

    printf("Original String: %s\n", str);

    // Reversing the string
    for (int i = 0; i < length / 2; i++) {
        char temp = str[i];
        str[i] = str[length - 1 - i];
        str[length - 1 - i] = temp;
    }

    printf("Reversed String: %s\n", str);

    return 0; // Returning 0 to indicate successful execution
}

Output:

Original String: Hello
Reversed String: olleH

Program 2: Check if a String is a Palindrome

Example:

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

bool isPalindrome(char str[]);

int main() {
    char str[] = "madam";

    if (isPalindrome(str)) {
        printf("The string is a palindrome.\n");
    } else {
        printf("The string is not a palindrome.\n");
    }

    return 0; // Returning 0 to indicate successful execution
}

bool isPalindrome(char str[]) {
    int length = strlen(str);

    for (int i = 0; i < length / 2; i++) {
        if (str[i] != str[length - 1 - i]) {
            return false;
        }
    }

    return true;
}

Output:

The string is a palindrome.

Program 3: Count the Number of Vowels in a String

Example:

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

int countVowels(char str[]);

int main() {
    char str[] = "Hello World";
    int vowelCount = countVowels(str);

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

    return 0; // Returning 0 to indicate successful execution
}

int countVowels(char str[]) {
    int count = 0;
    int length = strlen(str);

    for (int i = 0; i < length; i++) {
        if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' ||
            str[i] == 'o' || str[i] == 'u' || str[i] == 'A' ||
            str[i] == 'E' || str[i] == 'I' || str[i] == 'O' ||
            str[i] == 'U') {
            count++;
        }
    }

    return count;
}

Output:

Number of vowels: 3

Conclusion

Strings are a fundamental data structure in C used for handling text. By understanding how to declare, initialize, and manipulate strings, you can perform a wide range of text processing tasks. C provides various standard library functions for working with strings, making it easier to perform common operations such as calculating the length, copying, concatenating, and comparing strings. Mastering strings in C is essential for effective programming, as they are widely used in many applications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top