String Utilities
Common string manipulation functions: trimming, splitting, replacing
Description
A collection of string utility functions for common operations like trimming whitespace, splitting strings, and replacing substrings.
Features
- Trim whitespace
- Split by delimiter
- Replace substrings
- Case conversion
Code
#ifndef STRING_UTILS_H#define STRING_UTILS_H#include <stdlib.h>#include <string.h>#include <ctype.h>char* trim(char* str) { if (str == NULL) return NULL; // Trim leading whitespace while (isspace((unsigned char)*str)) str++; if (*str == 0) return str; // Trim trailing whitespace char* end = str + strlen(str) - 1; while (end > str && isspace((unsigned char)*end)) end--; end[1] = '\0'; return str;}char* str_replace(const char* str, const char* old, const char* new_str) { if (str == NULL || old == NULL || new_str == NULL) return NULL; size_t old_len = strlen(old); size_t new_len = strlen(new_str); size_t str_len = strlen(str); // Count occurrences int count = 0; const char* pos = str; while ((pos = strstr(pos, old)) != NULL) { count++; pos += old_len; } // Allocate result size_t result_len = str_len + count * (new_len - old_len); char* result = (char*)malloc(result_len + 1); if (result == NULL) return NULL; // Replace char* dest = result; const char* src = str; while (*src) { if (strncmp(src, old, old_len) == 0) { memcpy(dest, new_str, new_len); dest += new_len; src += old_len; } else { *dest++ = *src++; } } *dest = '\0'; return result;}void to_lowercase(char* str) { if (str == NULL) return; for (int i = 0; str[i]; i++) { str[i] = tolower((unsigned char)str[i]); }}void to_uppercase(char* str) { if (str == NULL) return; for (int i = 0; str[i]; i++) { str[i] = toupper((unsigned char)str[i]); }}#endif
#include "string_utils.h"#include <stdio.h>int main() { char str1[] = " Hello World "; printf("Original: '%s'\n", str1); printf("Trimmed: '%s'\n", trim(str1)); const char* original = "Hello World"; char* replaced = str_replace(original, "World", "Universe"); if (replaced) { printf("Replaced: %s\n", replaced); free(replaced); } char str2[] = "Hello World"; to_lowercase(str2); printf("Lowercase: %s\n", str2); return 0;}
Comments
No comments yet. Be the first to comment!
Please login to leave a comment.