String Functions in C

C provides a set of standard library functions for string manipulation, available in the <string.h> header file.

Common String Functions

Function Description
strlen(s)Returns the length of string s
strcpy(dest, src)Copies string src to dest
strncpy(dest, src, n)Copies first n characters of src to dest
strcat(dest, src)Appends string src to dest
strcmp(s1, s2)Compares strings s1 and s2
strchr(s, c)Returns pointer to first occurrence of character c in string s
strstr(haystack, needle)Returns pointer to first occurrence of substring needle in haystack

Examples of String Functions

1. Calculating String Length

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

int main() {
    char str[] = "Hello, World!";
    int length = strlen(str);
    printf("Length of string: %d\n", length);
    return 0;
}

2. Copying Strings

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

int main() {
    char src[] = "Source String";
    char dest[20];
    strcpy(dest, src);
    printf("Destination String: %s\n", dest);
    return 0;
}

3. Comparing Strings

#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;
}

Best Practices

  • Include <string.h> to access string functions.
  • Ensure destination arrays are large enough to hold the copied or concatenated strings.
  • Use strncpy() and strncat() to prevent buffer overflows.

Don'ts

  • Don't use strcpy() without ensuring the destination array is large enough.
  • Don't compare strings using the == operator; use strcmp() instead.
  • Don't forget that string functions may not handle overlapping memory areas correctly.

Key Takeaways

  • String functions provide powerful tools for manipulating strings in C.
  • Proper use of these functions enhances code efficiency and safety.
  • Always be mindful of buffer sizes to prevent security vulnerabilities.