String Functions in C
1. strlen() – Length of a String
strlen() returns the total number of characters in a string **excluding** the null terminator '\0'.
- Prototype:
size_t strlen(const char *str) - Counts characters until '\0' is found
- Used to calculate string size dynamically
Example: strlen()
#include <stdio.h>
#include <string.h>
int main() {
char word[] = "Programming";
printf("Length: %lu", strlen(word));
return 0;
}
2. strcpy() – Copy One String to Another
strcpy() copies the entire source string (including '\0') into the destination array.
- Prototype:
char* strcpy(char *dest, const char *src) - Destination must have enough space
- Used to duplicate strings
Example: strcpy()
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "Hello World";
char dest[50];
strcpy(dest, src);
printf("Copied String: %s", dest);
return 0;
}
3. strcat() – Concatenate (Append) Strings
strcat() joins the second string to the end of the first string.
- Prototype:
char* strcat(char *dest, const char *src) - Dest must have enough unused space
- Used for joining first name + last name, etc.
Example: strcat()
#include <stdio.h>
#include <string.h>
int main() {
char first[50] = "Sourav ";
char last[] = "Sahu";
strcat(first, last);
printf("Full Name: %s", first);
return 0;
}
4. strcmp() – Compare Two Strings
strcmp() compares two strings lexicographically (character-by-character).
- Returns 0 → strings are equal
- Returns +ve → first string is greater
- Returns -ve → second string is greater
- Case-sensitive
Example: strcmp()
#include <stdio.h>
#include <string.h>
int main() {
char a[] = "Apple";
char b[] = "Orange";
if(strcmp(a, b) == 0)
printf("Strings are equal");
else
printf("Strings are different");
return 0;
}
5. strupr() & strlwr() – Case Conversion
These functions convert entire strings to **uppercase** or **lowercase**. ⚠ These functions are compiler-dependent but commonly available.
- strupr() → converts to UPPERCASE
- strlwr() → converts to lowercase
Example: strupr() & strlwr()
#include <stdio.h>
#include <string.h>
int main() {
char text1[] = "Welcome";
char text2[] = "PROGRAMMING";
printf("Uppercase: %s\n", strupr(text1));
printf("Lowercase: %s", strlwr(text2));
return 0;
}
6. strrev() – Reverse a String
strrev() reverses the characters inside a string. Like strupr(), this is also compiler-dependent.
Example: strrev()
#include <stdio.h>
#include <string.h>
int main() {
char word[] = "Sourav";
printf("Reversed: %s", strrev(word));
return 0;
}
7. strncpy(), strncat(), strncmp() – Safer Versions
These functions work like strcpy(), strcat(), strcmp() but with an extra parameter for maximum characters.
- strncpy(dest, src, n) → copy only n characters
- strncat(dest, src, n) → append n characters
- strncmp(a, b, n) → compare n characters
Example: strncpy()
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "Programming";
char dest[20];
strncpy(dest, src, 5);
dest[5] = '\0'; // manually add null
printf("Copied (5 chars): %s", dest);
return 0;
}
8. strchr() – Find First Occurrence of Character
strchr() searches a string and returns a pointer to the first occurrence of the given character. If not found, it returns NULL.
- Prototype:
char* strchr(const char *str, int ch) - Returns pointer → can be used for substring access
- Case-sensitive
Example: strchr()
#include <stdio.h>
#include <string.h>
int main() {
char text[] = "programming";
char *ptr = strchr(text, 'g');
if(ptr != NULL)
printf("Found at position: %ld", ptr - text);
else
printf("Not found");
return 0;
}
9. strrchr() – Find Last Occurrence of Character
strrchr() returns a pointer to the last occurrence of a character in a string.
- Prototype:
char* strrchr(const char *str, int ch) - Useful for processing file extensions
Example: strrchr()
#include <stdio.h>
#include <string.h>
int main() {
char text[] = "hello@example.com";
char *ptr = strrchr(text, '.');
printf("Last dot at index: %ld", ptr - text);
return 0;
}
10. strstr() – Find Substring
strstr() searches for the first occurrence of a substring inside a bigger string.
- Prototype:
char* strstr(const char *str, const char *substr) - Returns pointer where substring starts
- Returns NULL if not found
Example: strstr()
#include <stdio.h>
#include <string.h>
int main() {
char sentence[] = "I love programming in C.";
char *ptr = strstr(sentence, "programming");
if(ptr)
printf("Substring found: %s", ptr);
else
printf("Not found");
return 0;
}
11. strtok() – Tokenize (Split) a String
strtok() breaks a string into smaller tokens based on delimiters (space, comma, etc.).
- Prototype:
char* strtok(char *str, const char *delim) - Useful for splitting sentences, CSV data
- Modifies the original string
Example: strtok()
#include <stdio.h>
#include <string.h>
int main() {
char line[] = "C, Java, Python, HTML";
char *token = strtok(line, ", ");
while(token != NULL){
printf("%s\n", token);
token = strtok(NULL, ", ");
}
return 0;
}
12. memcpy() – Fast Memory Copy
memcpy() copies a block of memory from one location to another.
- Prototype:
void* memcpy(void *dest, const void *src, size_t n) - Faster than loop copying
- Does NOT handle overlapping memory safely
Example: memcpy()
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "DATA";
char dest[10];
memcpy(dest, src, 5);
printf("Copied: %s", dest);
return 0;
}
13. memmove() – Safe Memory Copy
memmove() works like memcpy but safely handles memory overlap.
- Prototype:
void* memmove(void *dest, const void *src, size_t n) - Recommended when arrays overlap
Example: memmove()
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "ABCDEFG";
memmove(str+2, str, 4);
printf("Result: %s", str);
return 0;
}
14. memcmp() – Compare Blocks of Memory
memcmp() compares two memory blocks byte-by-byte.
- Returns 0 → same
- Returns +ve or -ve based on difference
- Often used in binary data comparison
Example: memcmp()
#include <stdio.h>
#include <string.h>
int main() {
char a[] = "Hello";
char b[] = "Helxo";
int res = memcmp(a, b, 5);
printf("Result: %d", res);
return 0;
}
15. memset() – Fill Memory With a Value
memset() fills an array or memory block with a specific value.
- Prototype:
void* memset(void *str, int ch, size_t n) - Useful for resetting arrays
Example: memset()
#include <stdio.h>
#include <string.h>
int main() {
char arr[10];
memset(arr, '*', 9);
arr[9] = '\0';
printf("%s", arr);
return 0;
}
⭐ 16. strdup() – Duplicate a String (Dynamic Memory)
strdup() allocates memory and duplicates the given string. The new copy is stored in heap memory using malloc().
- Prototype:
char* strdup(const char *str) - Creates a dynamically allocated string
- Must free() the allocated memory
Example: strdup()
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char text[] = "WebTech Academy";
char *copy = strdup(text);
printf("Duplicate: %s", copy);
free(copy);
return 0;
}
⭐ 17. strndup() – Duplicate Limited Characters
strndup() duplicates a maximum of n characters and stores the result in heap memory.
- Safer alternative to strdup()
- Creates partial string copies
Example: strndup()
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char text[] = "Programming";
char *copy = strndup(text, 5);
printf("Partial Copy: %s", copy);
free(copy);
return 0;
}
⭐ 18. strcasecmp() – Case-Insensitive Compare (POSIX)
strcasecmp() compares two strings without considering uppercase or lowercase differences.
Example: strcasecmp()
#include <stdio.h>
#include <strings.h>
int main() {
if(strcasecmp("hello", "HELLO") == 0)
printf("Equal");
else
printf("Not Equal");
return 0;
}
⭐ 19. strncasecmp() – Compare n Characters (Ignore Case)
strncasecmp() compares only first n characters, ignoring case.
Example: strncasecmp()
#include <stdio.h>
#include <strings.h>
int main() {
if(strncasecmp("Program", "proGress", 4) == 0)
printf("Match");
else
printf("No Match");
return 0;
}
⭐ 20. strpbrk() – Search Any Matching Character
strpbrk() finds the first occurrence of any character from a given list inside a string.
- Useful for detecting vowels or special characters
Example: strpbrk()
#include <stdio.h>
#include <string.h>
int main() {
char text[] = "chatbot";
char *ptr = strpbrk(text, "aeiou");
printf("First vowel: %c", *ptr);
return 0;
}
⭐ 21. strspn() – Count Initial Matching Characters
strspn() returns the length of the initial segment that contains only characters from another set.
- Useful for validating numeric sequences
Example: strspn()
#include <stdio.h>
#include <string.h>
int main() {
char text[] = "12345ABC";
int count = strspn(text, "0123456789");
printf("Digits length: %d", count);
return 0;
}
⭐ 22. strcspn() – Opposite of strspn()
strcspn() returns the length of the segment before any character from a given list appears.
Example: strcspn()
#include <stdio.h>
#include <string.h>
int main() {
char email[] = "admin@example.com";
int pos = strcspn(email, "@");
printf("Username length: %d", pos);
return 0;
}
⭐ 23. strnlen() – Safer Version of strlen()
strnlen() limits the maximum characters to check and avoids infinite scanning.
Example: strnlen()
#include <stdio.h>
#include <string.h>
int main() {
char text[10] = {'H','e','l','l','o'};
printf("Length (max 10): %lu", strnlen(text, 10));
return 0;
}
⭐ 24. strchrnul() – Safe strchr() (GNU Extension)
strchrnul() returns a pointer to the NULL terminator if the searched character is not found.
Example: strchrnul()
#include <stdio.h>
#include <string.h>
int main() {
char text[] = "hello";
char *ptr = strchrnul(text, 'x');
printf("Pointer at: %c", *ptr);
return 0;
}
⭐ 25. basename() & dirname() – File Path Utilities
These functions extract filename and directory path from a complete file path.
- basename() → returns filename
- dirname() → returns folder path
Example: basename() and dirname()
#include <stdio.h>
#include <libgen.h>
int main() {
char path[] = "/home/user/documents/file.txt";
printf("File: %s\n", basename(path));
printf("Folder: %s", dirname(path));
return 0;
}
Practice Questions
- What is strlen()? How does it work internally?
- Difference between strcpy() and strncpy().
- Explain lexicographic comparison in strcmp().
- Why are strupr() and strrev() non-standard?
- Write differences between strcat() and strncat().