All String Functions in C

What is String Function in C ?

String functions in C are pre-defined functions that allow programmers to manipulate strings efficiently. They are part of the C standard library and provide various operations that simplify the process of working with character arrays.

1. String Length Calculation

strlen(): Getting the Length of a String

The strlen() function is used to calculate the length of a given string. It counts the number of characters in the string until it encounters the null-terminator character ('\0'), which marks the end of the string.

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

int main() {
    char str[] = "Hello, World!";
    int length = strlen(str);
    printf("Length of the string: %d\n", length);
    return 0;
}

Output:

Length of the string: 13

2. Concatenating Strings

strcat(): Concatenating Two Strings

The strcat() function is used to concatenate two strings. It appends the characters of the second string to the end of the first string, effectively merging them.

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

int main() {
    char dest[50] = "Hello, ";
    char src[] = "World!";
    strcat(dest, src);
    printf("Concatenated string: %s\n", dest);
    return 0;
}

Output:

Concatenated string: Hello, World!

3. Copying Strings

strcpy(): Copying One String to Another

The strcpy() function is used to copy the characters of one string to another. It overwrites the content of the destination string with the content of the source string.

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

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

Output:

Copied string: Original

4. Comparing Strings

strcmp(): Comparing Two Strings

The strcmp() function is used to compare two strings. It returns an integer value that indicates whether the strings are equal, or which one is lexicographically greater or smaller.

#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("str1 is less than str2\n");
    } else {
        printf("str1 is greater than str2\n");
    }

    return 0;
}

Output:

str1 is less than str2

5. Searching for Substrings

strstr(): Finding a Substring

The strstr() function is used to find the first occurrence of a substring within a given string. It returns a pointer to the first character of the found substring, or NULL if the substring is not found.

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

int main() {
    char sentence[] = "The quick brown fox jumps over the lazy dog";
    char substring[] = "fox";
    char *ptr = strstr(sentence, substring);

    if (ptr != NULL) {
        printf("Substring found at position: %ld\n", ptr - sentence);
    } else {
        printf("Substring not found\n");
    }

    return 0;
}

Output:

Substring found at position: 16

6. Extracting Substrings

strncpy(): Extracting a Substring

The strncpy() function is used to copy a specified number of characters from one string to another, allowing you to extract a substring.

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

int main() {
    char source[] = "Hello, World!";
    char destination[10];
    strncpy(destination, source + 7, 5);
    destination[5] = '\0';
    printf("Extracted substring: %s\n", destination);
    return 0;
}

Output:

Extracted substring: World

7. Modifying Strings

strchr(): Modifying a String

The strchr() function is used to locate the first occurrence of a character within a string. It returns a pointer to the located character or NULL if the character is not found.

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

int main() {
    char str[] = "Hello, World!";
    char *ptr = strchr(str, 'W');

    if (ptr != NULL) {
        *ptr = 'w'; // Change 'W' to 'w'
    }

    printf("Modified string: %s\n", str);
    return 0;
}

Output:

Modified string: Hello, world!

8. Converting Case

toupper() and tolower(): Converting Case

The toupper() function converts a character to uppercase, while the tolower() function converts a character to lowercase.

#include <stdio.h>
#include <ctype.h>

int main() {
    char letter = 'a';
    printf("Uppercase: %c\n", toupper(letter));
    printf("Lowercase: %c\n", tolower(letter));
    return 0;
}

Output:

Uppercase: A
Lowercase: a

9. Reversing Strings

Reversing a String

Reversing a string involves swapping the characters from the beginning with those from the end. This can be achieved using a loop or by using the strrev() function if available.

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

void reverseString(char str[]) {
    int length = strlen(str);
    for (int i = 0; i < length / 2; i++) {
        char temp = str[i];
        str[i] = str[length - 1 - i];
        str[length - 1 - i] = temp;
    }
}

int main() {
    char str[] = "Hello";
    reverseString(str);
    printf("Reversed string: %s\n", str);
    return 0;
}

Output:

Reversed string: olleH

10. Tokenizing Strings

strtok(): Breaking a String into Tokens

The strtok() function is used to tokenize a string into smaller parts based on a set of delimiter characters.

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

int main() {
    char sentence[] = "This is a sample sentence.";
    char delimiters[] = " ";
    char *token = strtok(sentence, delimiters);

    while (token != NULL) {
        printf("%s\n", token);
        token = strtok(NULL, delimiters);
    }

    return 0;
}

Output:

This
is
a
sample
sentence.

11. Removing White Spaces

Removing Extra Spaces from a String

Removing extra spaces from a string can be achieved by iterating through the string and collapsing consecutive spaces.

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

void removeExtraSpaces(char str[]) {
    int length = strlen(str);
    bool prevSpace = false;
    int destIndex = 0;

    for (int i = 0; i < length; i++) {
        if (str[i] != ' ' || !prevSpace) {
            str[destIndex++] = str[i];
            prevSpace = (str[i] == ' ');
        }
    }

    str[destIndex] = '\0';
}

int main() {
    char str[] = "   Hello,   World!   ";
    removeExtraSpaces(str);
    printf("Modified string: %s\n", str);
    return 0;
}

Output:

Modified string:  Hello, World!

12. Formatting Strings

Formatting Strings with sprintf()

The sprintf() function is used to format strings in a manner similar to printf(), but instead of printing to the console, it stores the formatted string in a character array.

#include <stdio.h>

int main() {
    char formatted[50];
    int value = 42;
    sprintf(formatted, "The value is: %d", value);
    printf("%s\n", formatted);
    return 0;
}

Output:

The value is: 42

13. Numeric to String Conversion

Converting Numbers to Strings

Converting numeric values to strings can be achieved using the sprintf() function or specialized functions like itoa().

#include <stdio.h>
#include <stdlib.h>

int main() {
    int number = 123;
    char str[10];
    sprintf(str, "%d", number);
    printf("Converted string: %s\n", str);
    return 0;
}

Output:

Converted string: 123

14. String Formatting with sprintf()

Custom String Formatting

The sprintf() function allows for custom string formatting, including specifying the number of digits, alignment, and padding.

#include <stdio.h>

int main() {
    int value = 5;
    char formatted[20];
    sprintf(formatted, "Value: %03d", value);
    printf("%s\n", formatted);
    return 0;
}

Output:

Value: 005

Frequently Asked Questions

1. Are string functions case-sensitive in C?

Yes, most string functions in C, such as strcmp() and strstr(), are case-sensitive. They distinguish between uppercase and lowercase characters.

2. Can I modify a string directly using string functions?

Some string functions, like strcpy() and strcat(), can modify strings directly. However, caution should be exercised to prevent buffer overflows.

3. How do I reverse a string without using additional functions?

You can reverse a string by swapping characters from the beginning with those from the end using a loop.

4. What is the purpose of the null-terminator character in C strings?

The null-terminator character ('\0') marks the end of a string in C. It is used to indicate where the string’s contents conclude.

5. Is it possible to tokenize a string with multiple delimiters?

Yes, you can tokenize a string with multiple delimiters by calling the strtok() function multiple times with different delimiters.