Course Content
C Tutorial
About Lesson

String Manipulation (string.h)

String manipulation is a fundamental aspect of C programming, facilitated by the string.h library. This library equips developers with a suite of functions to manipulate strings efficiently. Understanding these functions is crucial for effective C programming.

Declaring Strings

In C, strings are arrays of characters terminated by a null character . For instance:

char myString[] = "Hello, World!";

Common String Functions

1. strlen():

This function calculates the length of a string by counting characters until the null terminator.

char str[] = "Example";
int length = strlen(str); // length will be 7
2. strcpy() and strncpy():

These functions copy one string to another. strcpy() copies the entire string, while strncpy() allows specifying the number of characters to copy.

char source[] = "Copy this string";
char destination[20];

strcpy(destination, source); // destination now holds "Copy this string"

3. strcmp() and strncmp():

These functions compare two strings. strcmp() compares entire strings, while strncmp() compares a specific number of characters.

char str1[] = "apple";
char str2[] = "banana";

int result = strcmp(str1, str2); // result will be negative

4. strcat() and strncat():

These functions concatenate strings. strcat() appends one string to another, while strncat() allows specifying the number of characters to concatenate.

char dest[20] = "Hello";
char src[] = ", World!";

strcat(dest, src); // dest now holds "Hello, World!"

String Manipulation Best Practices

  • Buffer Overflow: Be cautious of buffer overflows when manipulating strings. Ensure that the destination buffer has enough space to accommodate the result.

  • Null Termination: Always terminate strings with to mark the end of a string properly.

  • Boundary Conditions: Pay attention to boundary conditions while using string functions to prevent unexpected behavior or errors