Zone Of Makos

Menu icon

Strings in C

In the C programming language, strings are sequences of characters stored as arrays. They are used to represent text or a sequence of characters. In this lesson, we'll explore how strings are used in C, how to work with them, and some important functions for manipulating strings.

Creating and Initializing Strings

In C, strings are represented as character arrays terminated by a null character '\0'. You can create and initialize strings in various ways:


char str1[] = "Hello, world!";     // Initializing using a string literal
char str2[10] = {'H', 'i', '\0'};  // Initializing character by character
char str3[20];
strcpy(str3, "Welcome");           // Copying a string using strcpy()

String Functions in C

C provides several built-in functions for working with strings. Here are some commonly used string functions:

  • strlen() : Returns the length of a string.
  • strcpy() : Copies one string to another.
  • strcat() : Concatenates (appends) one string to another.
  • strcmp() : Compares two strings and returns an integer indicating their relationship.
  • strchr() : Searches for a character in a string.
  • strstr() : Searches for a substring in a string.

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

int main() {
    char str1[] = "Hello";
    char str2[] = "World";
    char str3[20];

    printf("Length of str1: %d\n", strlen(str1));
    
    strcpy(str3, str1);
    printf("Copied string: %s\n", str3);
    
    strcat(str1, str2);
    printf("Concatenated string: %s\n", str1);
    
    if (strcmp(str1, str2) == 0) {
        printf("Strings are equal\n");
    } else {
        printf("Strings are not equal\n");
    }
    
    char *ptr = strchr(str1, 'o');
    printf("First occurrence of 'o' in str1: %s\n", ptr);
    
    char *subStr = strstr(str1, "ell");
    printf("Substring 'ell' found in str1: %s\n", subStr);
    
    return 0;
}

Conclusion

Strings are an important concept in the C programming language. They are represented as character arrays terminated by a null character '\0'. C provides several functions for working with strings, allowing you to perform operations such as copying, concatenating, comparing, and searching. Understanding how to work with strings in C is essential for developing applications that involve text processing.

If you don't understand what the functions are, don't worry we'll cover those topics in the following lessons. Happy coding!