C String Functions

Built-in functions for string manipulation

🛠️ What are String Functions?

C provides a rich set of built-in string functions in the string.h library. These functions simplify common string operations like copying, comparing, concatenating, and searching, making string manipulation efficient and reliable.


#include <string.h>
char str1[20] = "Hello";
char str2[20] = "World";
strcat(str1, str2);  // Result: "HelloWorld"
                                    

String Function Categories

📏

Length Functions

Calculate string length

strlen("Hello")  // Returns 5
📋

Copy Functions

Copy strings safely

strcpy(dest, source)
🔗

Concatenation

Join strings together

strcat(str1, str2)
⚖️

Comparison

Compare string values

strcmp(str1, str2)

🔹 strlen() - String Length

The strlen() function returns the number of characters in a string, excluding the null terminator. This built-in string library function helps determine string length for validation and processing. For example, strlen("Hello") returns 5, while an empty string returns 0. Understanding string length is essential for buffer management, string comparison, and preventing buffer overflow attacks in C programming.

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

int main() {
    char name[] = "Programming";
    char empty[] = "";
    char sentence[] = "Hello World!";
    
    printf("Length of '%s': %d\n", name, strlen(name));
    printf("Length of empty string: %d\n", strlen(empty));
    printf("Length of '%s': %d\n", sentence, strlen(sentence));
    
    // Using strlen in loops
    printf("Characters in '%s': ", name);
    for(int i = 0; i < strlen(name); i++) {
        printf("%c ", name[i]);
    }
    printf("\n");
    
    return 0;
}

Output:

Length of 'Programming': 11

Length of empty string: 0

Length of 'Hello World!': 12

Characters in 'Programming': P r o g r a m m i n g

🔹 strcpy() and strncpy() - String Copy

String copying transfers content from one string variable to another using strcpy() or strncpy(). The strcpy(destination, source) function copies the entire source string, including the null terminator. The safer strncpy(destination, source, n) limits copying to n characters, preventing buffer overflows. Always ensure destination buffer has sufficient space to prevent security vulnerabilities and memory corruption issues.

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

int main() {
    char source[] = "Hello World";
    char dest1[20];
    char dest2[20];
    
    // strcpy - copies entire string
    strcpy(dest1, source);
    printf("Copied string: %s\n", dest1);
    
    // strncpy - copies n characters
    strncpy(dest2, source, 5);
    dest2[5] = '\0';  // Add null terminator
    printf("First 5 characters: %s\n", dest2);
    
    // Copy string literal
    strcpy(dest1, "New String");
    printf("New content: %s\n", dest1);
    
    return 0;
}

Output:

Copied string: Hello World

First 5 characters: Hello

New content: New String

🔹 strcat() and strncat() - String Concatenation

String concatenation joins two strings together using strcat() or strncat() functions. The strcat(str1, str2) function appends str2 to the end of str1, combining both strings. The safer strncat(str1, str2, n) appends only n characters, preventing buffer overflow. These functions are essential for building dynamic strings, constructing messages, and manipulating text data in your C applications.

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

int main() {
    char str1[50] = "Hello";
    char str2[] = " World";
    char str3[50] = "Good";
    char str4[] = " Morning Everyone";
    
    // strcat - concatenate entire string
    strcat(str1, str2);
    printf("After strcat: %s\n", str1);
    
    // strncat - concatenate n characters
    strncat(str3, str4, 8);  // Add only " Morning"
    printf("After strncat: %s\n", str3);
    
    // Chain concatenations
    strcpy(str1, "C");
    strcat(str1, " is");
    strcat(str1, " awesome!");
    printf("Chained: %s\n", str1);
    
    return 0;
}

Output:

After strcat: Hello World

After strncat: Good Morning

Chained: C is awesome!

🔹 strcmp() and strncmp() - String Comparison

String comparison determines if two strings are equal or establishes their lexicographic order using comparison functions. The strcmp(str1, str2) returns 0 if strings are equal, negative if str1 is less, or positive if str1 is greater. The strncmp(str1, str2, n) compares only the first n characters. These functions enable sorting, validation, and decision-making based on string content in your programs.

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

int main() {
    char str1[] = "Apple";
    char str2[] = "Banana";
    char str3[] = "Apple";
    
    // strcmp returns: 0 if equal, <0 if str1 < str2, >0 if str1 > str2
    int result1 = strcmp(str1, str2);
    int result2 = strcmp(str1, str3);
    int result3 = strcmp(str2, str1);
    
    printf("strcmp('%s', '%s') = %d\n", str1, str2, result1);
    printf("strcmp('%s', '%s') = %d\n", str1, str3, result2);
    printf("strcmp('%s', '%s') = %d\n", str2, str1, result3);
    
    // Practical usage
    if(strcmp(str1, str3) == 0) {
        printf("'%s' and '%s' are equal\n", str1, str3);
    }
    
    // strncmp - compare first n characters
    char word1[] = "Programming";
    char word2[] = "Program";
    
    if(strncmp(word1, word2, 7) == 0) {
        printf("First 7 characters match\n");
    }
    
    return 0;
}

Output:

strcmp('Apple', 'Banana') = -1

strcmp('Apple', 'Apple') = 0

strcmp('Banana', 'Apple') = 1

'Apple' and 'Apple' are equal

First 7 characters match

🔹 Search Functions - strchr() and strstr()

Search functions locate characters and substrings within larger strings for text processing tasks. The strchr(string, character) finds the first occurrence of a character, returning a pointer to its location or NULL if not found. The strstr(string, substring) searches for a complete substring. These functions return pointers allowing further string manipulation from the found position, enabling powerful text searching and parsing capabilities.

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

int main() {
    char text[] = "Programming in C is fun!";
    char *ptr;
    
    // strchr - find first occurrence of character
    ptr = strchr(text, 'g');
    if(ptr != NULL) {
        printf("First 'g' found at position: %ld\n", ptr - text);
        printf("Substring from first 'g': %s\n", ptr);
    }
    
    // strrchr - find last occurrence of character
    ptr = strrchr(text, 'g');
    if(ptr != NULL) {
        printf("Last 'g' found at position: %ld\n", ptr - text);
    }
    
    // strstr - find substring
    ptr = strstr(text, "in C");
    if(ptr != NULL) {
        printf("'in C' found at position: %ld\n", ptr - text);
        printf("Substring from 'in C': %s\n", ptr);
    }
    
    // Check if substring exists
    if(strstr(text, "Python") == NULL) {
        printf("'Python' not found in the text\n");
    }
    
    return 0;
}

Output:

First 'g' found at position: 3

Substring from first 'g': gramming in C is fun!

Last 'g' found at position: 7

'in C' found at position: 12

Substring from 'in C': in C is fun!

'Python' not found in the text

🔹 Practical String Function Examples

Real-world applications of string functions:

Password Validation:

int validatePassword(char password[]) {
    if(strlen(password) < 8) {
        printf("Password too short!\n");
        return 0;
    }
    if(strstr(password, "123") != NULL) {
        printf("Password too simple!\n");
        return 0;
    }
    return 1;  // Valid password
}

Name Formatting:

void formatName(char fullName[], char first[], char last[]) {
    strcpy(fullName, first);
    strcat(fullName, " ");
    strcat(fullName, last);
}

Word Counter:

int countWords(char sentence[]) {
    int count = 0;
    char *word = strtok(sentence, " ");
    while(word != NULL) {
        count++;
        word = strtok(NULL, " ");
    }
    return count;
}

🧠 Test Your Knowledge

Which function would you use to find the length of a string?