CSE NotesCSE Notes
Simplifying Complexity

In C, a string is essentially an array of characters. Unlike other programming languages where strings are considered a built-in data type, C does not have a specific “string” type. Instead, strings are represented as an array of characters terminated by a special null character ('\0'), which marks the end of the string.

1. Declaring and Initializing Strings

Declaration and Initialization:

  • A string is an array of characters, and each element in the array is a character.
  • The string must end with the null character ('\0') to mark its termination.
#include <stdio.h>

int main() {
    // Declare a string (character array)
    char str1[] = "Hello, World!";
    char str2[20] = "Hello";  // Size is larger than the string length

    printf("String 1: %s\n", str1);
    printf("String 2: %s\n", str2);

    return 0;
}

2. Important String Operations

Here are some common operations that you can perform on strings in C:

a) String Length (strlen()):

To get the length of a string (number of characters excluding the null character), you can use the strlen() function from the string.h library.

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

int main() {
    char str[] = "Hello, World!";
    printf("Length of the string: %lu\n", strlen(str));  // %lu for size_t return type
    return 0;
}

b) String Copy (strcpy()):

To copy one string into another, use strcpy() from string.h.

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

int main() {
    char src[] = "Hello, World!";
    char dest[50];

    strcpy(dest, src);  // Copy contents of src to dest
    printf("Source: %s\n", src);
    printf("Destination: %s\n", dest);

    return 0;
}

c) String Concatenation (strcat()):

To concatenate two strings, use strcat() from string.h. It appends the second string to the end of the first string.

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

int main() {
    char str1[50] = "Hello, ";
    char str2[] = "World!";

    strcat(str1, str2);  // Concatenate str2 to str1
    printf("Concatenated String: %s\n", str1);

    return 0;
}

d) String Comparison (strcmp()):

To compare two strings, use strcmp(). It returns:

  • 0 if the strings are equal.
  • A negative value if the first string is less than the second.
  • A positive value if the first string is greater than the second.
#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "Apple";
    char str2[] = "Banana";

    if (strcmp(str1, str2) == 0) {
        printf("Strings are equal.\n");
    } else {
        printf("Strings are not equal.\n");
    }

    return 0;
}

e) String Search (strstr()):

To find a substring within a string, use strstr(). It returns a pointer to the first occurrence of the substring.

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

int main() {
    char str[] = "This is a sample string";
    char *result = strstr(str, "sample");

    if (result != NULL) {
        printf("Substring found: %s\n", result);  // Prints "sample string"
    } else {
        printf("Substring not found.\n");
    }

    return 0;
}

3. String Input/Output

a) Reading Strings:

To read a string from the user, use scanf() with %s, or fgets() to allow spaces in the string.

  • scanf(): Reads until the first whitespace character (space, tab, or newline).
  • fgets(): Reads an entire line, including spaces, up to a specified length.
#include <stdio.h>

int main() {
    char str[100];
    
    // Using scanf (it will stop reading at the first space)
    printf("Enter a string: ");
    scanf("%s", str);  // Stops at the first whitespace
    printf("You entered: %s\n", str);
    
    // Using fgets (can include spaces)
    printf("Enter a string with spaces: ");
    fgets(str, sizeof(str), stdin);  // Reads an entire line
    printf("You entered: %s\n", str);

    return 0;
}

4. Common String Functions in string.h

  • strlen(): Returns the length of the string (not including the null character).
  • strcpy(): Copies a string to another string.
  • strcat(): Appends one string to the end of another string.
  • strcmp(): Compares two strings lexicographically.
  • strchr(): Searches for the first occurrence of a character in a string.
  • strstr(): Searches for the first occurrence of a substring in a string.
  • strtok(): Breaks a string into tokens (used for parsing).

5. String as Character Arrays:

Remember that in C, strings are essentially arrays of characters. This means you can treat a string as a regular array of characters and manipulate its elements directly.

#include <stdio.h>

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

    // Accessing individual characters
    printf("First character: %c\n", str[0]);  // H
    printf("Second character: %c\n", str[1]); // e

    // Modifying a string element
    str[0] = 'J';
    printf("Modified string: %s\n", str);  // Jello

    return 0;
}

6. Multi-Dimensional Arrays of Strings (Array of Strings)

In C, an array of strings is essentially an array of character arrays (2D array). This is used to store multiple strings.

#include <stdio.h>

int main() {
    // Declare an array of strings (2D array of characters)
    char str[3][20] = {
        "Hello",
        "World",
        "C Programming"
    };

    // Printing the array of strings
    for (int i = 0; i < 3; i++) {
        printf("String %d: %s\n", i+1, str[i]);
    }

    return 0;
}

Conclusion:

  • Strings in C are handled as arrays of characters, and they require careful memory management, especially regarding the null-terminator ('\0').
  • Standard String Functions (strlen, strcpy, strcat, strcmp, etc.) in the <string.h> library can help you perform operations on strings easily.
  • Input and Output: Use scanf or fgets to take string input and printf to output strings.

Strings are a very important part of C programming, and understanding how to manipulate them effectively will help you work with text-based data in your applications.