String Functions in C

C provides a collection of powerful functions inside the <string.h> header file to work with strings. These functions help in copying, comparing, joining, finding length, converting case, reversing, and performing many operations on strings easily.

1. strlen() – Length of a String

strlen() returns the total number of characters in a string **excluding** the null terminator '\0'.

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.

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.

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).

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.

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.

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.

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.

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.

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.).

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.

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.

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.

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.

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().

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.

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.

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.

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.

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

  1. What is strlen()? How does it work internally?
  2. Difference between strcpy() and strncpy().
  3. Explain lexicographic comparison in strcmp().
  4. Why are strupr() and strrev() non-standard?
  5. Write differences between strcat() and strncat().

Practice Task

Write a program using string functions to: ✔ Read a full name ✔ Remove spaces ✔ Count vowels ✔ Convert to uppercase ✔ Reverse the name ✔ Print all outputs clearly