C String Functions
In this section, you'll learn about the most common string functions in C, which are defined in the <string.h> header file. These functions help you manipulate, compare, search, and transform strings efficiently.
Introduction to C String Functions
C doesn't have a dedicated string type. Instead, strings are represented as arrays of characters terminated by a null character ('\0'). To help work with these character arrays, C provides a set of standard library functions in the <string.h> header.
#include <string.h>  // Required to use string functions
Common String Functions
String Length: strlen()
The strlen() function returns the length of a string (excluding the null terminator).
size_t strlen(const char *str);
Example:
#include <stdio.h>
#include <string.h>
int main() {
    char message[] = "Hello, world!";
    size_t length = strlen(message);
    
    printf("The length of \"%s\" is %zu characters.\n", message, length);
    return 0;
}
Output:
The length of "Hello, world!" is 13 characters.
String Copy: strcpy() and strncpy()
The strcpy() function copies one string to another, while strncpy() copies a specified number of characters.
char *strcpy(char *dest, const char *src);
char *strncpy(char *dest, const char *src, size_t n);
strcpy() doesn't check if the destination buffer is large enough, which can lead to buffer overflows. strncpy() is safer but doesn't guarantee null-termination if the source is longer than n.
Example:
#include <stdio.h>
#include <string.h>
int main() {
    char source[] = "Copy this!";
    char destination1[20];
    char destination2[20];
    
    strcpy(destination1, source);
    printf("After strcpy(): %s\n", destination1);
    
    strncpy(destination2, source, 4);  // Copy only 4 characters
    destination2[4] = '\0';  // Manually add null terminator
    printf("After strncpy(): %s\n", destination2);
    
    return 0;
}
Output:
After strcpy(): Copy this!
After strncpy(): Copy
String Concatenation: strcat() and strncat()
These functions append one string to the end of another.
char *strcat(char *dest, const char *src);
char *strncat(char *dest, const char *src, size_t n);
Example:
#include <stdio.h>
#include <string.h>
int main() {
    char destination[50] = "Hello, ";
    char source[] = "world!";
    
    strcat(destination, source);
    printf("After strcat(): %s\n", destination);
    
    strncat(destination, " How are you?", 8);  // Append only 8 characters
    printf("After strncat(): %s\n", destination);
    
    return 0;
}
Output:
After strcat(): Hello, world!
After strncat(): Hello, world! How are
String Comparison: strcmp() and strncmp()
These functions compare two strings lexicographically.
int strcmp(const char *str1, const char *str2);
int strncmp(const char *str1, const char *str2, size_t n);
Return values:
- 0: Strings are equal
- < 0: First string is less than second
- > 0: First string is greater than second
Example:
#include <stdio.h>
#include <string.h>
int main() {
    char string1[] = "apple";
    char string2[] = "apple";
    char string3[] = "banana";
    
    printf("strcmp(string1, string2): %d\n", strcmp(string1, string2));
    printf("strcmp(string1, string3): %d\n", strcmp(string1, string3));
    printf("strcmp(string3, string1): %d\n", strcmp(string3, string1));
    
    return 0;
}
Output:
strcmp(string1, string2): 0
strcmp(string1, string3): -1
strcmp(string3, string1): 1
String Searching: strchr() and strstr()
strchr() finds the first occurrence of a character, while strstr() finds the first occurrence of a substring.
char *strchr(const char *str, int c);
char *strstr(const char *haystack, const char *needle);
Example:
#include <stdio.h>
#include <string.h>
int main() {
    char text[] = "The quick brown fox jumps over the lazy dog";
    char *result1, *result2;
    
    // Find first occurrence of 'o'
    result1 = strchr(text, 'o');
    if (result1) {
        printf("First 'o' found at position: %ld\n", result1 - text);
    }
    
    // Find substring "fox"
    result2 = strstr(text, "fox");
    if (result2) {
        printf("Substring \"fox\" found at position: %ld\n", result2 - text);
    }
    
    return 0;
}
Output:
First 'o' found at position: 12
Substring "fox" found at position: 16
Memory Operations: memcpy() and memset()
While not strictly string functions, these memory functions are commonly used with strings.
void *memcpy(void *dest, const void *src, size_t n);
void *memset(void *str, int c, size_t n);
Example:
#include <stdio.h>
#include <string.h>
int main() {
    char source[] = "Memory operations";
    char destination[20];
    
    // Copy memory
    memcpy(destination, source, 10);
    destination[10] = '\0';  // Add null terminator
    printf("After memcpy(): %s\n", destination);
    
    // Set memory
    memset(destination, '*', 5);
    destination[5] = '\0';  // Add null terminator
    printf("After memset(): %s\n", destination);
    
    return 0;
}
Output:
After memcpy(): Memory ope
After memset(): *****
Other Useful String Functions
strtok() - String Tokenization
Splits a string into tokens using specified delimiters.
#include <stdio.h>
#include <string.h>
int main() {
    char input[] = "apple,banana,orange,grape";
    char *token;
    
    // Get the first token
    token = strtok(input, ",");
    
    // Walk through other tokens
    while (token != NULL) {
        printf("%s\n", token);
        token = strtok(NULL, ",");
    }
    
    return 0;
}
Output:
apple
banana
orange
grape
strdup() - String Duplication
Creates a duplicate of a string by allocating memory and copying the string.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>  // For free()
int main() {
    char *original = "Dynamic memory";
    char *duplicate = strdup(original);
    
    if (duplicate) {
        printf("Original: %s\n", original);
        printf("Duplicate: %s\n", duplicate);
        
        // Remember to free the memory
        free(duplicate);
    }
    
    return 0;
}
strdup() is not part of the C standard, but it's widely available. For strict standard compliance, use malloc() and strcpy().
Best Practices for String Functions
- 
Always check for NULL before using strings: if (str != NULL) {
 // Use string functions safely
 }
- 
Ensure destination buffers are large enough: char dest[BUFFER_SIZE];
 if (strlen(source) < BUFFER_SIZE) {
 strcpy(dest, source);
 }
- 
Prefer strncpy(),strncat(), etc. over their unlimited counterparts.
- 
Always null-terminate strings when using strncpy():strncpy(dest, src, n);
 dest[n-1] = '\0'; // Ensure null-termination
- 
Handle the return values of string functions appropriately. 
Summary
String functions in C provide essential tools for working with text data. They allow you to:
- Determine string length with strlen()
- Copy strings with strcpy()andstrncpy()
- Combine strings with strcat()andstrncat()
- Compare strings with strcmp()andstrncmp()
- Search within strings using strchr()andstrstr()
- Manipulate memory with memcpy()andmemset()
- Split strings into tokens with strtok()
Always include the <string.h> header when using these functions and be mindful of buffer sizes to prevent memory corruption issues.
Practice Exercises
- Write a program that counts the number of occurrences of a specific character in a string.
- Create a function that reverses a string in place without using additional memory.
- Implement a simple string-based calculator that handles addition and subtraction.
- Write a program that converts a string to uppercase without using the standard library function.
💡 Found a typo or mistake? Click "Edit this page" to suggest a correction. Your feedback is greatly appreciated!