0
0
Cprogramming~5 mins

Common string operations

Choose your learning style9 modes available
Introduction

Strings are used to store text. Common operations help us read, change, and compare text easily.

When you want to find the length of a word or sentence.
When you need to join two pieces of text together.
When you want to check if two texts are the same.
When you want to copy text from one place to another.
When you want to find a smaller text inside a bigger text.
Syntax
C
strlen(string)       // Returns length of string
strcpy(dest, src)    // Copies src string to dest
strcat(dest, src)    // Adds src string at the end of dest
strcmp(str1, str2)   // Compares two strings
strstr(haystack, needle) // Finds needle in haystack

All strings in C end with a special character '\0' to mark the end.

Make sure destination arrays have enough space before copying or adding strings.

Examples
Finds the length of the string "Alice" which is 5.
C
char name[20] = "Alice";
int length = strlen(name);
Copies the string from name to copy.
C
char copy[20];
strcpy(copy, name);
Adds the name "Alice" to the greeting, making "Hello, Alice".
C
char greeting[30] = "Hello, ";
strcat(greeting, name);
Checks if the string name is exactly "Alice".
C
if (strcmp(name, "Alice") == 0) {
    // strings are equal
}
Sample Program

This program joins two words with a space, prints the combined string and its length, then checks if the word "World" is inside the combined string.

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

int main() {
    char first[20] = "Hello";
    char second[20] = "World";
    char combined[50];

    // Copy first into combined
    strcpy(combined, first);
    // Add a space
    strcat(combined, " ");
    // Add second into combined
    strcat(combined, second);

    printf("Combined string: %s\n", combined);
    printf("Length: %zu\n", strlen(combined));

    // Check if combined contains "World"
    if (strstr(combined, "World") != NULL) {
        printf("Found 'World' inside combined.\n");
    } else {
        printf("Did not find 'World'.\n");
    }

    return 0;
}
OutputSuccess
Important Notes

Always include <string.h> to use these string functions.

Be careful with buffer sizes to avoid errors or crashes.

Strings in C are arrays of characters ending with '\0'.

Summary

Use strlen to get string length.

Use strcpy to copy strings safely.

Use strcat to join strings.

Use strcmp to compare strings.

Use strstr to find a substring inside another string.