Advanced String Techniques
Memory Management in String Processing
Dynamic String Allocation
char* createDynamicString(const char* source) {
size_t length = strlen(source);
char* newString = malloc((length + 1) * sizeof(char));
if (newString != NULL) {
strcpy(newString, source);
}
return newString;
}
String Parsing Strategies
Tokenization Techniques
graph TD
A[Input String] --> B[strtok Function]
B --> C[Split into Tokens]
C --> D[Process Individual Tokens]
D --> E[Reconstruct/Analyze]
Token Parsing Example
#include <string.h>
void parseCSVLine(char* line) {
char* token;
char* delimiter = ",";
token = strtok(line, delimiter);
while (token != NULL) {
printf("Token: %s\n", token);
token = strtok(NULL, delimiter);
}
}
Advanced String Manipulation Functions
Function |
Purpose |
Complexity |
strstr() |
Substring search |
O(n*m) |
strchr() |
Character location |
O(n) |
strspn() |
Prefix matching |
O(n) |
Regular Expression Simulation
int matchPattern(const char* string, const char* pattern) {
while (*pattern) {
if (*pattern == '*') {
// Wildcard matching logic
return 1;
}
if (*string != *pattern) {
return 0;
}
string++;
pattern++;
}
return *string == '\0';
}
Memory-Safe String Operations
Custom Safe String Copy
size_t safeCopyString(char* destination,
const char* source,
size_t destSize) {
size_t sourceLen = strlen(source);
size_t copyLen = (sourceLen < destSize) ? sourceLen : destSize - 1;
memcpy(destination, source, copyLen);
destination[copyLen] = '\0';
return copyLen;
}
- Minimize memory allocations
- Use stack memory when possible
- Implement custom string handling
- Avoid repeated string traversals
void transformString(char* str) {
// In-place string transformation
for (int i = 0; str[i]; i++) {
if (islower(str[i])) {
str[i] = toupper(str[i]);
}
}
}
LabEx String Processing Workflow
graph TD
A[Input String] --> B[Validation]
B --> C[Memory Allocation]
C --> D[Transformation]
D --> E[Processing]
E --> F[Output/Storage]
Best Practices
- Always validate input strings
- Use buffer overflow prevention
- Implement error handling
- Consider memory efficiency
- Prefer standard library functions
Error Handling Strategies
char* processStringWithErrorHandling(const char* input) {
if (input == NULL) {
return NULL; // Early exit
}
// Safe processing logic
char* result = malloc(strlen(input) + 1);
if (result == NULL) {
// Memory allocation failed
return NULL;
}
// Process string
strcpy(result, input);
return result;
}