C string.h Library

C Tutorial

C string.h Library

In C string.h Library provides functions to manipulate and handle strings (character arrays). It’s one of the most widely used libraries for string operations.


📌 Common String Functions

1️⃣ String Length and Copy

FunctionDescription
strlen(const char *str)Returns the length of the string (excluding \0)
strcpy(char *dest, const char *src)Copies src string into dest
strncpy(char *dest, const char *src, size_t n)Copies first n characters of src to dest

Example:


 


2️⃣ String Concatenation

FunctionDescription
strcat(char *dest, const char *src)Appends src at the end of dest
strncat(char *dest, const char *src, size_t n)Appends first n characters of src to dest

Example:


 


3️⃣ String Comparison

FunctionDescription
strcmp(const char *str1, const char *str2)Compares two strings, returns 0 if equal
strncmp(const char *str1, const char *str2, size_t n)Compares first n characters
strcasecmp / strncasecmpCase-insensitive comparison (POSIX)

Example:


 


4️⃣ Searching in Strings

FunctionDescription
strchr(const char *str, int c)Returns pointer to first occurrence of c
strrchr(const char *str, int c)Returns pointer to last occurrence of c
strstr(const char *haystack, const char *needle)Returns pointer to first occurrence of needle substring

Example:


 


5️⃣ String Tokenization

FunctionDescription
strtok(char *str, const char *delim)Splits string into tokens based on delimiters

Example:


 


6️⃣ String Transformation

FunctionDescription
toupper(int c) / tolower(int c)Convert character case
memset(void *ptr, int value, size_t num)Fill memory with value
memcpy(void *dest, const void *src, size_t n)Copy memory block
memcmp(const void *ptr1, const void *ptr2, size_t n)Compare memory block

Example:


 


7️⃣ Dynamic String Example


 


📌 Summary Table

FunctionPurpose
strlenGet string length
strcpy, strncpyCopy strings
strcat, strncatConcatenate strings
strcmp, strncmpCompare strings
strchr, strrchrFind character in string
strstrFind substring
strtokTokenize string
toupper, tolowerConvert character case
memset, memcpy, memcmpManipulate memory

✅ Notes

  1. Strings in C are arrays of characters ending with \0.

  2. Always ensure enough space in destination arrays for strcpy/strcat.

  3. Prefer strncpy and strncat for safe operations.

  4. Use dynamic memory for strings of unknown length.

You may also like...