String Functions

Working with strings is a fundamental part of programming, and C provides a rich set of built-in functions to manipulate strings efficiently. These functions are part of the <string.h> library and make string operations much easier than writing everything from scratch.

Including the String Library

Before using any string functions, you need to include the string header file:

#include <string.h>

Common String Functions

1. strlen() - String Length

The strlen() function returns the length of a string (number of characters excluding the null terminator).

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

int main() {
    char name[] = "Alice";
    int length = strlen(name);
    printf("Length of '%s' is %d\n", name, length);
    return 0;
}

2. strcpy() - String Copy

The strcpy() function copies one string to another. Think of it as photocopying a document!

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

int main() {
    char source[] = "Hello World";
    char destination[20];
    
    strcpy(destination, source);
    printf("Copied string: %s\n", destination);
    return 0;
}

3. strcat() - String Concatenation

The strcat() function joins two strings together, like connecting two train cars.

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

int main() {
    char greeting[20] = "Hello ";
    char name[] = "Bob";
    
    strcat(greeting, name);
    printf("Result: %s\n", greeting);
    return 0;
}

4. strcmp() - String Comparison

The strcmp() function compares two strings and returns:

  • 0 if strings are equal
  • Negative value if first string is lexicographically smaller
  • Positive value if first string is lexicographically greater
#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("'%s' comes before '%s'\n", str1, str2);
    } else {
        printf("'%s' comes after '%s'\n", str1, str2);
    }
    return 0;
}

Safe String Functions

strncpy() - Safe String Copy

Unlike strcpy(), strncpy() allows you to specify the maximum number of characters to copy, preventing buffer overflow.

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

int main() {
    char source[] = "This is a long string";
    char destination[10];
    
    strncpy(destination, source, 9);
    destination[9] = '\0';  // Ensure null termination
    
    printf("Copied: %s\n", destination);
    return 0;
}

strncat() - Safe String Concatenation

Similar to strcat(), but with a limit on characters to append.

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

int main() {
    char result[20] = "Hello ";
    char addition[] = "Beautiful World";
    
    strncat(result, addition, 5);  // Only append first 5 characters
    printf("Result: %s\n", result);
    return 0;
}

String Search Functions

strchr() - Find Character

Finds the first occurrence of a character in a string.

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

int main() {
    char text[] = "Programming";
    char *position = strchr(text, 'g');
    
    if (position != NULL) {
        printf("Found 'g' at position: %ld\n", position - text);
    } else {
        printf("Character not found\n");
    }
    return 0;
}

strstr() - Find Substring

Finds the first occurrence of a substring within a string.

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

int main() {
    char sentence[] = "Learning C programming is fun";
    char *found = strstr(sentence, "programming");
    
    if (found != NULL) {
        printf("Found substring: %s\n", found);
    } else {
        printf("Substring not found\n");
    }
    return 0;
}

Quick Reference Table

FunctionPurposeExample Usage
strlen(str)Get string lengthint len = strlen("hello");
strcpy(dest, src)Copy stringstrcpy(name, "John");
strcat(dest, src)Concatenate stringsstrcat(greeting, name);
strcmp(str1, str2)Compare stringsif (strcmp(a, b) == 0)
strchr(str, ch)Find characterchar *pos = strchr(text, 'x');
strstr(str, substr)Find substringchar *pos = strstr(text, "hello");

Important Notes

  • Always ensure your destination string has enough space when copying or concatenating
  • Remember that strings in C are null-terminated
  • Use the "safe" versions (strncpy, strncat) when possible to prevent buffer overflows
  • String functions modify the original string (except comparison and search functions)

These string functions are your toolkit for text manipulation in C. Master them, and you'll be able to handle most string-related tasks efficiently!