String Functions
09 January 2025 11:06 AM
Here’s a comprehensive example for each string function. I'll group them by functionality for better understanding.
Copy a String
1. char *strcpy(char *destination, const char *source) - The strcpy function is used to copy a string
from one location to another in C.
2. char *strncpy(char *destination, const char *source, size_t num) - The strncpy function in
C is used to copy a specified number of characters from one string to another.
Prototype of strcpy: char *strcpy(char *destination, const char *source);
Explanation of Parameters
destination (char *):
○ A pointer to the memory location where the string will be copied.
○ This should have enough space allocated to hold the source string, including the null terminator ('\0').
source (const char *):
○ A pointer to the string to be copied.
○ Declared as const to indicate that the function does not modify the source string.
Return Value
• Returns:
○ A pointer to the destination string.
• This allows chaining of string operations, as the returned pointer can be used immediately.
How It Works
• strcpy copies the string (character by character) from the source to the destination until the null terminator ('\0') is
encountered.
• The null terminator is also copied to the destination, ensuring the copied string is properly terminated.
Usage Example
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Hello, World!";
char destination[50]; // Allocate enough space
// Copy source to destination
strcpy(destination, source);
// Output
printf("Source: %s\n", source);
printf("Destination: %s\n", destination);
return 0;
}
Output:
Source: Hello, World!
Destination: Hello, World!
Key Points
1. No Bounds Checking:
○ strcpy does not check if the destination has enough space.
○ If the destination array is smaller than the source, it will cause a buffer overflow, leading to undefined behavior.
Safe Alternative: strncpy
strncpy(destination, source, n);
○ Limits the number of characters copied to n.
2. Null Terminator:
The null terminator from the source string is always copied to destination.
STRING Page 1
○ The null terminator from the source string is always copied to destination.
3. Chaining:
○ Since strcpy returns a pointer to destination, it can be used in expressions:
printf("%s\n", strcpy(destination, source));
Internal Representation
Internally, strcpy works like this:
char *strcpy(char *destination, const char *source) {
char *ptr = destination;
while ((*ptr++ = *source++) != '\0'); // Copy until null terminator
return destination;
}
Common Issues
a. Buffer Overflow:
a. Ensure destination has enough space for the string and the null terminator.
b. Example of incorrect usage:
char source[] = "Hello, World!";
char destination[5]; // Not enough space
strcpy(destination, source); // Undefined behavior
b. Overwriting Existing Data:
a. strcpy overwrites all contents of destination.
How to copy a specific number characters?
char *strncpy(char *destination, const char *source, size_t num) - The strncpy function in C is used
to copy a specified number of characters from one string to another.
destination (char *):
○ A pointer to the memory location where the string will be copied.
○ Must have enough space to hold the copied characters, including the null terminator ('\0'), if applicable.
source (const char *):
○ A pointer to the string to be copied.
○ Declared as const to ensure that the function does not modify the source string.
num (size_t):
○ The maximum number of characters to copy from the source.
○ This can be less than or equal to the length of the source string.
Return Value
• Returns:
○ A pointer to the destination string.
Key Characteristics
1. Partial Copy:
○ If the length of the source string is less than num, the remaining characters in the destination are filled with null
characters ('\0').
2. No Automatic Null Terminator:
○ If the length of the source string is greater than or equal to num, the copied string will not include a null
terminator unless explicitly added.
Usage Example
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Hello, World!";
char destination[20];
STRING Page 2
char destination[20];
// Copy up to 5 characters from source to destination
strncpy(destination, source, 5);
// Manually null-terminate the destination string, length of the source is greater
than n=5
destination[5] = '\0';
// Output
printf("Source: %s\n", source);
printf("Destination: %s\n", destination);
return 0;
}
Output:
Source: Hello, World!
Destination: Hello
Common Issues
1. No Null Termination:
○ If num is less than the length of the source, the destination string is not null-terminated.
○ Always ensure null termination if necessary:
strncpy(destination, source, num);
destination[num] = '\0'; // Add null terminator manually
2. Buffer Overflow:
○ Ensure destination has enough space for the copied characters and potential null terminators.
Concatenating Two Strings
1. char *strcat(char *destination, const char *source);
2. char *strncat(char *destination, const char *source, size_t num);
Both strcat and strncat are functions in C used to concatenate (append) one string to another. Here's an explanation
of each, along with their prototypes and usage examples.
Description
• Appends the source string to the end of the destination string.
• The null terminator ('\0') of the destination is overwritten by the first character of source.
• A null terminator is added to the combined string.
Parameters
1. destination (char *):
○ The string to which the source will be appended.
○ Must have enough space to hold both the original destination and the source, including the null terminator.
2. source (const char *):
○ The string to append.
○ Must be null-terminated.
3. num (size_t):
○ The maximum number of characters to append from source.
Return Value
• A pointer to the destination string.
Example
#include <stdio.h>
#include <string.h>
int main() {
char destination[50] = "Hello, ";
char source[] = "World!";
STRING Page 3
char source[] = "World!";
strcat(destination, source);
printf("Concatenated String: %s\n", destination);
return 0;
}
Output:
Concatenated String: Hello, World!
Example
#include <stdio.h>
#include <string.h>
int main() {
char destination[50] = "Hello, ";
char source[] = "World!";
strncat(destination, source, 3); // Append only the first 3 characters of source
printf("Concatenated String: %s\n", destination);
return 0;
}
Output:
Concatenated String: Hello, Wor
Key Differences Between strcat and strncat
Feature strcat strncat
Control over appended Appends the entire source string. Appends at most num characters.
characters
Safety May cause buffer overflows if destination is not Safer due to the num parameter.
large enough.
Null termination Always null-terminates the result. Null-terminates if enough space is available
in destination.
Important Notes
1. Buffer Overflow:
○ Both strcat and strncat assume that the destination buffer has enough space for the concatenated string.
○ Always ensure that the destination buffer is large enough to hold the result.
2. Null Terminator:
○ Both functions ensure the resulting string in destination is null-terminated.
Comparing Two Strings
1. int strcmp(const char *str1, const char *str2) - Compares two null-terminated strings str1 and
str2 lexicographically (character by character). The comparison is case-sensitive.
2. int strncmp(const char *str1, const char *str2, size_t num) - Compares up to num
characters of two null-terminated strings str1 and str2 lexicographically. The comparison stops after num characters, or
when a null terminator is encountered in either string. The comparison is case-sensitive.
3. int _stricmp(const char *str1, const char *str2) - stricmp is a case-insensitive version of the
standard strcmp function. It compares two strings lexicographically without considering the case of the characters. If
not exit in standard library same need to be implemented.
4. int _strnicmp(const char *str1, const char *str2, size_t num) - is a case-insensitive, length-
limited string comparison function, mainly used in Windows / MSVC environments.
STRING Page 4
5. Some similar function like _stricmp tested on VS code editor, windows 11.
○ printf("%d", stricmp("Hello", "hello"));
○ printf("%d", strcmpi("Hello", "hello"));
○ printf("%d", _stricmp("Hello", "hello"));
○ printf("%d", strcasecmp("Hello", "hello"));
Parameters
• str1 (const char *): The first null-terminated string to compare.
• str2 (const char *): The second null-terminated string to compare
• num (size_t): The maximum number of characters to compare.
Return Value
• < 0: If str1 is lexicographically less than str2 (ignoring case).
• 0: If str1 and str2 are equal (ignoring case).
• > 0: If str1 is lexicographically greater than str2 (ignoring case).
Example
strcmp(str1, str2)
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
int result = strcmp(str1, str2);
printf("Comparison Result: %d\n", result); // Negative if str1 < str2
return 0;
}
strncmp(str1, str2, n)
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "Helium";
int result = strncmp(str1, str2, 3);
printf("Comparison Result (partial): %d\n", result); // 0 if first 3 chars are
equal
return 0;
}
Find length of a String Length
size_t strlen(const char *str) - The strlen function in C is used to calculate the length of a null-terminated string
(excluding the null character \0).
Parameters
○ str (const char *): A pointer to the null-terminated string whose length you want to determine.
Return Value
○ Returns the length of the string (number of characters before the null character \0).
○ The return type is size_t, an unsigned integer type.
Points to Remember
1. Null character not counted: The null terminator \0 is not included in the length.
2. Input Must Be Null-Terminated: If the string is not null-terminated, strlen can lead to undefined behavior (e.g., reading out of
STRING Page 5
2. Input Must Be Null-Terminated: If the string is not null-terminated, strlen can lead to undefined behavior (e.g., reading out of
bounds or infinite loops).
3. Works on Read-Only Strings: Since strlen does not modify the string, you can use it with const char* pointers or string literals.
4. Does Not Check Buffer Size: strlen assumes the string is valid and null-terminated. It does not limit how far it reads, which can
lead to issues if the string is improperly formed.
Searching a character
1. char *strchr(const char *str, int ch) - Searches for the first occurrence of a character in a string.
2. char *strrchr(const char *str, int ch) - Searches for the last occurrence of a character in a string.
Parameters:
○ str: The null-terminated string to search.
○ ch: The character to find (converted to char).
Returns:
○ Pointer to the first occurrence of ch in str.
○ NULL if the character is not found.
Searching a substring
1. char *strstr(const char *haystack, const char *needle) - Searches for the first occurrence of a
substring in a string
Returns:
○ Pointer to the first occurrence of needle in haystack.
○ NULL if needle is not found.
Tokenization a String
The strtok() function in C is used to split a string into tokens (substrings) based on specified delimiters. It is a part of the string.h library.
char *strtok(char *str, const char *delim);
Parameters:
1. str:
○ The string to tokenize.
○ On the first call, pass the string to tokenize.
○ On subsequent calls, pass NULL to continue tokenizing the same string.
2. delim:
○ A string containing delimiter characters that separate tokens.
Returns:
• A pointer to the next token (substring).
• Returns NULL when no more tokens are found.
Key Points
1. Destructive Function: strtok() modifies the input string by replacing delimiters with \0 (null characters).
2. Stateful Function: It remembers the string being tokenized between calls using an internal static pointer.
3. Not Thread-Safe: Since it uses a static variable, it is not safe for multithreaded programs.
How It Works
1. The first call to strtok():
STRING Page 6
1. The first call to strtok():
○ Takes the input string and a delimiter.
○ Returns the first token.
2. Subsequent calls with NULL:
○ Continue tokenizing the same string until all tokens are extracted.
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello,World,This,Is,C"; // Input string
const char delim[] = ","; // Delimiter
// First call to strtok
char *token = strtok(str, delim);
// Extract and print tokens
while (token != NULL) {
printf("Token: %s\n", token);
token = strtok(NULL, delim); // Subsequent calls with NULL
}
return 0;
}
Output
Token: Hello
Token: World
Token: This
Token: Is
Token: C
Step-by-Step Execution
First Call:
strtok(str, delim)
Searches for the first delimiter in str.
Replaces the delimiter with \0.
Returns the first token ("Hello").
Subsequent Calls:
strtok(NULL, delim)
Continues from where the previous call left off.
Repeats the process until no tokens remain.
Notes
1. Input String Modification:
○ strtok() changes the input string by replacing delimiters with \0.
○ Use a copy of the original string if needed later.
2. Delimiter Handling:
○ Multiple consecutive delimiters are treated as a single delimiter.
○ Leading delimiters are ignored.
3. Static Pointer:
○ The function uses a static pointer to track the tokenization process.
Example: Multiple Delimiters
#include <stdio.h>
STRING Page 7
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "apple;orange,banana:grape"; // Input string
const char delim[] = ";,:";
char *token = strtok(str, delim);
while (token != NULL) {
printf("Token: %s\n", token);
token = strtok(NULL, delim);
}
return 0;
}
Conversion Function
1. strupr(char *str) - Convert a given string into upper case, need to be implement if
not present in standard library.
2. Strlwr(char *str) - Convert a given string into lower case, need to be implement if
not present in standard library.
Reverse a string
1. strrev(char *str) or _strrev(chat *str) - reverse the given string, if function not
exist in standard libraray need to be implement.
Memory Functions
1. void *memcpy(void *destination, const void *source, size_t n) - it copies n bytes of
memory from the memory location pointed to by source to the memory location pointed to by destination. Works
on raw memory (not strings only)
○ Copies byte by byte
○ Does not stop at '\0'
○ Very fast (often optimized by compiler)
When to prefer memcpy() over strcpy() in C?
You should prefer memcpy() instead of strcpy() when your task involves explicit control over memory and size, or
when the data is not a null-terminated string.
Ex - Copy Integer Array
#include <stdio.h>
#include <string.h>
int main()
{
int nums[] = {1, 2, 3, 4, 5};
const int size = sizeof(nums);
int dup_nums[size];
memcpy(dup_nums, nums, size);
for (int i = 0; i < 5; i++)
{
printf("%d ", dup_nums[i]);
}
}
STRING Page 8
}
When the string may contain '\0' in between
• strcpy() stops copying at the first '\0'.
• memcpy() copies exactly n bytes, including any null bytes.
7. String Duplication
Feature strdup() strcpy()
Memory allocation ✔ Yes (heap) ❌ No
Destination required ❌ No ✔ Yes
Copies '\0' ✔ Yes ✔ Yes
Needs free() ✔ Yes ❌ No
Standard POSIX (not ISO C) ISO C
Risk of overflow ❌ Lower ✔ High (if dest too small)
From <[Link]
char *strdup(const char *str);
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char str[] = "Hello, World!";
char *copy = strdup(str);
if (copy) {
printf("Duplicated String: %s\n", copy);
free(copy); // Free allocated memory
}
return 0;
}
8. Case Conversion
strlwr(str) and strupr(str)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void toLowerCase(char *str) {
while (*str) {
*str = tolower(*str);
str++;
}
}
void toUpperCase(char *str) {
while (*str) {
*str = toupper(*str);
str++;
}
}
int main() {
char str[] = "Hello, World!";
toLowerCase(str);
printf("Lowercase: %s\n", str);
toUpperCase(str);
printf("Uppercase: %s\n", str);
STRING Page 9
printf("Uppercase: %s\n", str);
return 0;
}
Finding a substring using strspn()
Definition:
The strspn() function in C is used to calculate the length of the initial segment of a string that contains only characters from a given set of
characters (i.e., a substring starting from the beginning of the string that only contains characters found in the set of delimiters).
Prototype:
size_t strspn(const char *str1, const char *str2);
Parameters:
str1: The string to search.
str2: A string containing the set of characters to match against.
Returns:
The function returns the number of characters at the beginning of str1 that are all found in str2.
If no characters in str1 match str2, it returns 0.
How It Works:
• strspn() scans the string str1 from the beginning and counts how many consecutive characters match any of the characters in str2.
• The function stops as soon as it encounters a character in str1 that is not in str2, and it returns the number of characters matched up
to that point.
• If the first character in str1 does not match any character in str2, it returns 0.
Code Example
#include <stdio.h>
#include <string.h>
int main() {
const char *str1 = "12345abcde";
const char *str2 = "1234567890"; // Set of allowed characters (digits)
size_t result = strspn(str1, str2); // Find the length of the initial segment of
digits
printf("The length of the initial segment of digits: %zu\n", result);
return 0;
}
Explanation:
The string str1 = "12345abcde" is checked for consecutive characters that match the set str2 = "1234567890" (digits).
The function counts characters from the beginning of str1 that are all digits, which are "12345", so the result is 5.
STRING Page 10