Predefined String Functions in C

Predefined String Functions in C Language with Examples

In this article, I will discuss the Predefined String Functions in C Language with Examples. Please read our previous articles discussing Strings in C Language with Examples. 

String Manipulation in C

String manipulation in C involves a variety of operations, such as concatenation, comparison, copying, and more. C doesn’t have a string type in the same way as languages like Python or Java; instead, strings are represented as arrays of characters terminated by a null character (‘\0’). Here’s an overview of how strings are typically handled in C:

  • Assignment: Strings cannot be directly assigned using the = operator after declaration. Instead, use strcpy or similar functions from <string.h>.
  • Concatenation: The + operator doesn’t concatenate strings in C. Use strcat or strncat from <string.h>.
  • Comparison: The == operator compares the pointers, not the string content. Use strcmp or strncmp for content comparison.
  • Accessing Characters: Individual characters can be accessed and modified using the subscript operator [], like str[index].
  • Pointer Arithmetic: You can use pointers to manipulate strings, such as incrementing a pointer to traverse the string.
  • Length Calculation: There’s no operator to find the length of a string directly. Use strlen from <string.h>.
  • Formatting Strings: The sprintf and snprintf functions can be used for formatting strings.
  • Substrings and Searches: To find substrings or characters, use functions like strstr or strchr.
  • Copying Strings: For copying strings, strcpy and strncpy are used.

strcpy() Function in C:

The strcpy() function in C is a standard library function defined in the <string.h> header file. It is used to copy the contents of one string into another.

Function Prototype: char *strcpy(char *dest, const char *src);
Parameters:

  • dest: A pointer to the destination array where the content will be copied.
  • src: A string (character array) that is to be copied.

Return Value: The strcpy() function returns a pointer to the destination string dest.
Behavior: The strcpy() function copies the string pointed to by src, including the terminating null byte (‘\0’), to the buffer pointed to by dest. The strings may not overlap, and the destination string dest must be large enough to receive the copy.

Here’s a basic example demonstrating its usage:

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

int main() {
    char source[] = "Hello, world!";
    char destination[50];  // Make sure this is large enough to hold the source string

    strcpy(destination, source);

    printf("Source String: %s\n", source);
    printf("Destination String: %s\n", destination);

    return 0;
}

In this example:

  • source is the string we want to copy.
  • destination is the string into which we copy the content of the source. It’s important to ensure that the destination is large enough to hold the contents of the source, including the null terminator (‘\0’).
  • The strcpy(destination, source); statement copies the source’s content into the destination.
  • The printf functions then print out the contents of both source and destination to verify the copy.
Safety Considerations:
  • strcpy() does not perform bounds checking, and thus can lead to buffer overflows if the destination buffer is not large enough to hold the source string. To mitigate this, many programs use strncpy() instead, which allows specifying the maximum number of characters to copy.
  • Difference from strncpy(): strncpy() is similar to strcpy() but includes an additional parameter to specify the number of characters to copy, providing a safeguard against buffer overflows.

strlen() Function in C:

The strlen() function in C is a standard library function defined in the <string.h> header file. It is used to calculate the length of a string. It returns the number of characters in the string, excluding the null terminator (‘\0’).

Function Prototype: size_t strlen(const char *str);

  • Parameter: str: A pointer to the string whose length is to be found.
  • Return Value: The function returns the number of characters in the string pointed to by str, excluding the terminating null byte (‘\0’).
  • Behavior: The strlen() computes the length of the string str up to, but not including, the terminating null character. The function iterates through each string character, counting them until it encounters the null character.

Here’s an example to demonstrate its usage:

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

int main() {
    char str[] = "Hello, World!";
    int len = strlen(str); // Calculates the length of str

    printf("The length of '%s' is %d characters.\n", str, len);

    return 0;
}

In this example:

  • str is a string initialized to “Hello, World!”.
  • strlen(str) calculates the length of str and stores it in the integer variable len.
  • The printf function then outputs the length of the string.

Remember, strlen() counts the number of characters up to but not including the null terminator. This function is very useful in scenarios where you need to know the length of a string to perform operations like string manipulation, memory allocation, and more.

strrev() Function in C:

The strrev() function in C is used to reverse a string. However, it’s important to note that strrev() is not a standard function in the C Standard Library as defined by ANSI/ISO C. This means it may not be available in all C compilers or environments, especially those that adhere strictly to standard C. It’s primarily found in the Borland C Compiler and certain versions of the Microsoft C Compiler but is not part of the standard library in compilers like GCC. For environments where strrev() is available, it’s typically found in <string.h> and works as follows:

Function Prototype: char *strrev(char *str);

  • Parameter: str: A pointer to the string to be reversed.
  • Return Value: The function returns a pointer to the reversed string.
  • Behavior: strrev() reverses the string in place. The reversal is done on the original string, not on a copy.

Here’s an example to demonstrate its usage:

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

int main() {
    char str[] = "Hello, World!";
    strrev(str); // Reverses the string

    printf("Reversed String: %s\n", str);

    return 0;
}

In this code:

  • The string str is initialized with “Hello, World!”.
  • strrev(str) reverses the string in place.
  • The printf function then prints the reversed string.

If strrev() is unavailable in your compiler, you can write a simple function to reverse a string using two pointers or by swapping characters from the start and end of the string until the middle is reached. Here’s a simple implementation:

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

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

int main() {
    char str[] = "Hello, World!";
    reverseString(str); // Reverses the string using a custom function

    printf("Reversed String: %s\n", str);

    return 0;
}

In this custom function:

  • reverseString takes a string and reverses it by swapping characters from the beginning and end, moving towards the center.
  • strlen(str) is used to determine the length of the string.
  • A for loop is used to swap the characters until the middle of the string is reached.

strcat() Function in C:

The strcat() function in C is a standard library function used to concatenate (append) one string to the end of another. It’s defined in the <string.h> header file. It takes two strings as arguments: the destination string, which must be large enough to hold the concatenated result, and the source string, which is appended to the end of the destination string. Here’s an overview of how strcat() works:

Function Prototype: char *strcat(char *dest, const char *src);

Parameters:

  • dest: A pointer to the destination string. This string should have enough space to hold the concatenated resulting string.
  • src: A pointer to the source string that will be appended to dest.

Return Value: The function returns a pointer to the resulting string dest.

Behavior:

  • strcat() appends the string pointed to by src to the end of the string pointed to by dest. The terminating null character of dest is overwritten by the first character of src, and a new null character (‘\0’) is appended at the end of the concatenated string.
  • It’s important that the dest string has enough space to accommodate the additional characters from src to prevent buffer overflow, which can lead to undefined behavior.

Here’s an example demonstrating how to use strcat():

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

int main() {
    char dest[50] = "Hello, "; // Ensure dest is large enough to hold the concatenated result
    char src[] = "World!";

    strcat(dest, src); // Appends src to dest

    printf("Concatenated String: %s\n", dest);

    return 0;
}

In this example:

  • dest is the destination string, initialized with “Hello, “. It’s important to ensure that dest has enough space to hold the final concatenated string. That’s why we declare it with a size of 50 characters, which is more than enough for this example.
  • src is the source string containing “World!”.
  • strcat(dest, src) appends src to the end of dest.
  • The printf function is then used to print the concatenated string.
Safety Considerations:
  • Unlike some safer string functions (like strncat), strcat() does not allow you to specify a maximum length for the destination buffer, which can lead to buffer overflows if not used carefully.
  • Always ensure that the destination array (dest) is large enough to hold the resulting string, which includes the original content of dest, the content of src, and the null terminator.
  • Difference from strncat(): strncat() is similar to strcat() but includes an additional parameter to specify the maximum number of characters to append, providing a safeguard against buffer overflows.

strupr() Function in C:

The strupr() function converts a string to uppercase in C. However, it’s important to note that strupr() is not part of the standard C library as defined by ANSI/ISO C, meaning it’s unavailable in all C compilers or environments, particularly those that adhere strictly to standard C, like GCC. It’s more commonly found in compilers associated with Microsoft and Borland. For environments where strupr() is available, it’s typically found in <string.h> and operates as follows:

Function Prototype (if available): char *strupr(char *str);

  • Parameter: str: A pointer to the string to be converted to uppercase.
  • Return Value: The function returns a pointer to the converted string.
  • Behavior: strupr() converts each character in the string pointed to by str to uppercase. It typically does this in place, meaning the original string is modified.

If strupr() is available in your compiler, here’s how you can use it:

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

int main() {
    char str[] = "Hello, World!";
    strupr(str); // Converts the string to uppercase

    printf("Uppercase String: %s\n", str);

    return 0;
}

In this code:

  • The string str is initialized with “Hello, World!”.
  • strupr(str) converts all the lowercase characters in the string to uppercase.
  • The printf function then prints the converted uppercase string.

If strupr() is unavailable in your compiler, you can write a custom function to convert a string to uppercase. Here’s an example of how you could do it:

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

void toUpperCase(char *str) {
    while(*str) {
        *str = toupper((unsigned char) *str);
        str++;
    }
}

int main() {
    char str[] = "Hello, World!";
    toUpperCase(str); // Converts the string to uppercase using a custom function

    printf("Uppercase String: %s\n", str);

    return 0;
}

In this custom function:

  • toUpperCase takes a string and iterates through each character.
  • toupper((unsigned char) *str) converts each character to uppercase. The cast to unsigned char ensures the toupper function behaves correctly with negative char values.
  • The string is modified in place, character by character, until the null terminator is reached.

strlwr() Function in C:

Similar to strupr(), the strlwr() function is used to convert a string to lowercase in C. However, strlwr() is not a part of the standard C library and may not be available in all C compilers, particularly those that stick closely to the ANSI/ISO standards, like GCC. It’s more commonly found in Microsoft or Borland compilers. For environments where strlwr() is available, it typically functions as follows:

Function Prototype (if available): char *strlwr(char *str);

  • Parameter: str: A pointer to the string to be converted to lowercase.
  • Return Value: The function returns a pointer to the converted string.
  • Behavior: strlwr() converts each character in the string pointed to by str to lowercase. This is usually done in place, modifying the original string.

If strlwr() is available in your compiler, here’s how you can use it:

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

int main() {
    char str[] = "Hello, WORLD!";
    strlwr(str); // Converts the string to lowercase

    printf("Lowercase String: %s\n", str);

    return 0;
}

In this code:

  • The string str is initialized with “Hello, WORLD!”.
  • strlwr(str) converts all the uppercase characters in the string to lowercase.
  • The printf function then prints the converted lowercase string.

If strlwr() is unavailable in your compiler, you can implement a custom function to convert a string to lowercase. Here’s how you can do it:

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

void toLowerCase(char *str) {
    while(*str) {
        *str = tolower((unsigned char) *str);
        str++;
    }
}

int main() {
    char str[] = "Hello, WORLD!";
    toLowerCase(str); // Converts the string to lowercase using a custom function

    printf("Lowercase String: %s\n", str);

    return 0;
}

In this custom function:

  • toLowerCase iterates through each character in the string.
  • tolower((unsigned char) *str) converts each character to lowercase. The cast to unsigned char ensures proper behavior of the tolower function, especially with negative char values.
  • The string is modified in place, character by character, until the null terminator is reached.

strcmp() Function in C:

The strcmp() function in C is used for comparing two strings. It’s included in the <string.h> header file. It compares the strings character by character using the ASCII values of the characters and returns an integer based on the result of the comparison:

  • If the first string equals the second string, strcmp() returns 0.
  • If the first string is greater than the second string, it returns a positive value.
  • If the first string is less than the second string, it returns a negative value.

Here’s an overview of how strcmp() works:

Function Prototype: int strcmp(const char *str1, const char *str2);
Parameters: str1, str2: Pointers to the two null-terminated strings that are to be compared.

Return Value:

The function returns an integer:

  • 0: if str1 and str2 are equal.
  • A negative value: if str1 is less than str2.
  • A positive value: if str1 is greater than str2.
Behavior:
  • strcmp() compares the two strings character by character using the ASCII values of the characters.
  • The comparison is done lexicographically. When a mismatch is found or the end of either string is reached, the function returns.
  • A common misconception is that the return value is always -1, 0, or 1, but it can be any negative or positive value indicating the lexicographic order.

Use Cases: strcmp() is commonly used in sorting algorithms for strings, in searching algorithms, and anywhere string equality or ordering needs to be assessed.

Here’s an example demonstrating how to use strcmp():

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

int main() {
    char str1[] = "Hello";
    char str2[] = "World";
    char str3[] = "Hello";

    int result1 = strcmp(str1, str2); // Compares str1 with str2
    int result2 = strcmp(str1, str3); // Compares str1 with str3

    printf("Comparing '%s' and '%s': %d\n", str1, str2, result1);
    printf("Comparing '%s' and '%s': %d\n", str1, str3, result2);

    return 0;
}

In this example:

  • str1 is compared with str2. Since they are different, result1 will not be 0. The specific value (positive or negative) depends on comparing their ASCII values.
  • str1 is compared with str3. They are identical, so result2 will be 0.
  • The printf functions are used to output the results of these comparisons.

Remember, strcmp() performs a case-sensitive comparison. If you need a case-insensitive comparison, you would use strcasecmp() in POSIX-compliant systems or implement a custom function.

strstr() Function in C

The strstr() function in C is a standard library function used to find the first occurrence of a substring within another string. It’s included in the <string.h> header file. This function returns a pointer to the beginning of the found substring in the string or NULL if the substring is not found. Here’s an overview of how strstr() works:

Function Prototype: char *strstr(const char *haystack, const char *needle);
Parameters:

  • haystack: The string to be searched.
  • needle: The substring to find in haystack.
Return Value:
  • If the needle is found in the haystack, the function returns a pointer to the first occurrence of the needle.
  • If the needle is not found, the function returns NULL.
  • If the needle points to an empty string, strstr() returns the haystack.

Behavior: strstr() searches for the first occurrence of the substring needle within the string haystack. The search does not include the terminating null characters.

Use Cases: strstr() is commonly used in text processing tasks like parsing, searching for patterns in strings, or extracting substrings.

Here’s an example demonstrating how to use strstr():

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

int main() {
    char str[] = "Hello, World! Welcome to programming.";
    char substr[] = "World";

    char *ptr = strstr(str, substr); // Finds 'World' in str

    if(ptr) {
        printf("Substring found: '%s'\n", ptr);
    } else {
        printf("Substring not found.\n");
    }

    return 0;
}

In this example:

  • str is the main string in which we are searching for the substring.
  • substr is the substring we are looking for.
  • strstr(str, substr) searches for substr in str and returns a pointer to the first occurrence of substr.
  • ptr will point to the first occurrence of “World” in str, which is part of the original str string. Therefore, printing ptr will print “World! Welcome to programming.” since it starts printing from the found substring to the end of str.
  • If the substring is not found, strstr returns NULL, and the corresponding message is printed.

Note: The function performs a case-sensitive search. For a case-insensitive search, you would need a function like strcasestr() (available in some environments) or implement your own case-insensitive search function.

strchr() function in C

The strchr() function in C is a standard library function used to find the first occurrence of a character in a string. It’s included in the <string.h> header file. It returns a pointer to the first occurrence of the character in the string or NULL if the character is not found. Here’s an overview of how strchr() works:

Function Prototype: char *strchr(const char *str, int c);
Parameters:

  • str: A pointer to the string in which the search is performed.
  • c: The character to search for. It is passed as an int, but is internally converted to a char.

Return Value:

  • If the character c is found within the string str, the function returns a pointer to the first occurrence of c.
  • If c is not found, the function returns NULL.

Behavior:

  • strchr() scans the string pointed to by str from the beginning to the end (including the terminating null character), looking for the first occurrence of the character c.
  • The null character \0 can also be searched with this function.

Use Cases: strchr() is commonly used in string parsing tasks, such as tokenizing a string, finding the position of certain characters, or processing parts of a string based on character occurrence.

Here’s an example demonstrating how to use strchr():

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

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

    char *ptr = strchr(str, ch); // Finds the first occurrence of 'W' in str

    if(ptr) {
        printf("Character '%c' found at position: %ld\n", ch, ptr - str);
    } else {
        printf("Character '%c' not found in the string.\n", ch);
    }

    return 0;
}

In this example:

  • str is the string in which we are searching for the character.
  • ch is the character we are looking for.
  • strchr(str, ch) searches for ch in str and returns a pointer to the first occurrence of ch.
  • ptr will point to the first occurrence of ‘W’ in str.
  • If the character is found, the program calculates the character’s position in the string by subtracting the base address of the string (str) from the pointer (ptr). This gives the index (position) of the character in the string.
  • If the character is not found, strchr returns NULL, and the corresponding message is printed.

In the next article, I will discuss How to Find the Length of a String in C Language with Examples. Here, in this article, I try to explain String Predefined Functions in C Language with Examples. I hope you enjoy this String Predefined Functions in C Language with Examples article. I would like to have your feedback. Please post feedback, questions, or comments about this String PreDefined Functions in C Language Language with Examples article.

Leave a Reply

Your email address will not be published. Required fields are marked *