4.2) Strings in C

Strings in C are used to represent sequences of characters, such as words or sentences.

In C, strings are actually arrays of characters, with an extra character \0 (null terminator) at the end to indicate the end of the string.

Let’s explore strings in detail with simple explanations and code examples.

Declaring and Initializing Strings

Strings are declared as character arrays using the syntax: char string_name[length];

You can initialize strings during declaration or assign values later.

Example: Declaring and Initializing a String

#include <stdio.h>

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

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

    return 0;
}

Explanation:

  • In this example, a string named greeting is declared and initialized with the characters “Hello”.
  • The size of the character array should be one more than the length of the string to accommodate the null terminator.

Inputting Strings

You can use scanf to input strings, but be careful about buffer overflows.

Example: Inputting a String:

#include <stdio.h>

int main() {
    char name[20];

    printf("Enter your name: ");
    scanf("%s", name);

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

    return 0;
}

Explanation:

  • In this example, we declare a character array name with enough space to hold a name.
  • We use scanf to input the name. However, it stops reading at the first whitespace (space, tab, newline), so it’s not suitable for reading multi-word names.

String Functions

strlen – String Length:

The strlen function returns the length of a string, excluding the null terminator.

Example: Using strlen

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

int main() {
    char message[] = "Hello, world!";
    int length = strlen(message);

    printf("Length of the message: %d\n", length);

    return 0;
}

Output:

Length of the message: 13

strcpy – String Copy:

The strcpy function copies one string into another.

Example: Using strcpy

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

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

    strcpy(destination, source);

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

    return 0;
}

Output:

Copied string: Hello

strcat – String Concatenation:

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

Example: Using strcat

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

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

    strcat(greeting, name);

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

    return 0;
}

Output:

Greeting: Hello, Alice

strcmp – String Comparison:

The strcmp function compares two strings and returns an integer indicating their relationship.

Example: Using strcmp

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

int main() {
    char str1[] = "apple";
    char str2[] = "banana";

    int result = strcmp(str1, str2);

    if (result == 0) {
        printf("Strings are equal\n");
    } else if (result < 0) {
        printf("str1 is less than str2\n");
    } else {
        printf("str1 is greater than str2\n");
    }

    return 0;
}

Output:

str1 is less than str2

strchr – String Character Search

The strchr function searches for the first occurrence of a character in a string and returns a pointer to that location.

Example: Using strchr

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

int main() {
    char sentence[] = "Hello, world!";
    char *ptr = strchr(sentence, 'w');

    if (ptr != NULL) {
        printf("Found 'w' at position: %ld\n", ptr - sentence);
    } else {
        printf("'w' not found\n");
    }

    return 0;
}

Output:

Found ‘w’ at position: 7

strstr – String Substring Search

The strstr function searches for the first occurrence of a substring in a string and returns a pointer to that location.

Example: Using strstr

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

int main() {
    char text[] = "C programming is fun!";
    char keyword[] = "programming";

    char *ptr = strstr(text, keyword);

    if (ptr != NULL) {
        printf("Keyword found at position: %ld\n", ptr - text);
    } else {
        printf("Keyword not found\n");
    }

    return 0;
}

Output:

Keyword found at position: 2

Important Considerations:

  1. Null Terminator: Strings in C are null-terminated, which means they end with a null character (\0), not a visible character.
  2. Buffer Overflows: Be careful when inputting strings with scanf to avoid buffer overflows. Use fgets for safer input.
  3. String Functions: The string.h library provides useful functions for string manipulation, but always ensure you handle string lengths and null terminators correctly.
  4. Comparisons: When comparing strings, use functions like strcmp instead of direct comparison operators (==, !=).

Strings are fundamental in programming for working with textual data. Understanding how strings are represented as character arrays and how to use string functions helps you handle text effectively in your programs.

Leave a Reply