mirror of
https://gitlab.com/80486DX2-66/gists
synced 2024-11-08 18:02:23 +05:30
C: add str_replace.*
This commit is contained in:
parent
eb34ee33b3
commit
130179ab6b
78
c-programming/strings/str_replace.c
Normal file
78
c-programming/strings/str_replace.c
Normal file
@ -0,0 +1,78 @@
|
||||
/*
|
||||
* str_replace.c
|
||||
*
|
||||
* Author: Intel A80486DX2-66
|
||||
* License: Creative Commons Zero 1.0 Universal
|
||||
*
|
||||
* To-Do:
|
||||
* - add ability to replace from the end (negative value of max_count)
|
||||
*/
|
||||
|
||||
#include "str_replace.h"
|
||||
|
||||
char* str_replace(
|
||||
const char* str,
|
||||
const char* substr,
|
||||
const char* replacement,
|
||||
ssize_t max_count
|
||||
) {
|
||||
/*
|
||||
* input arguments:
|
||||
* max_count: N <= 0 for all replacements, N > 0 for N replacement
|
||||
*
|
||||
* the output string should be freed!
|
||||
*/
|
||||
size_t substr_len = strlen(substr),
|
||||
replacement_len = strlen(replacement),
|
||||
count = 0;
|
||||
const char* p = str;
|
||||
|
||||
// count the number of occurrences of the substring
|
||||
for (; (p = strstr(p, substr)) != NULL; count++) {
|
||||
if (max_count >= 0 && count >= (size_t) max_count)
|
||||
break;
|
||||
p += substr_len;
|
||||
}
|
||||
|
||||
// allocate a buffer to hold the modified string
|
||||
size_t new_len = strlen(str) + count * (replacement_len - substr_len);
|
||||
|
||||
char* result = malloc((new_len + 1) * sizeof(char));
|
||||
if (result == NULL) {
|
||||
perror("calloc");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
const char* q = str;
|
||||
char* r = result;
|
||||
for (; (p = strstr(q, substr)) != NULL && count > 0; count--) {
|
||||
size_t len = p - q;
|
||||
memcpy(r, q, len);
|
||||
r += len;
|
||||
memcpy(r, replacement, replacement_len);
|
||||
r += replacement_len;
|
||||
q = p + substr_len;
|
||||
}
|
||||
strcpy(r, q);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
#ifdef TEST
|
||||
#include <stdio.h>
|
||||
|
||||
int main(void) {
|
||||
const char* str = "Hello; peace! This is a peaceful test.",
|
||||
* substr = "peace",
|
||||
* replacement1 = "universe",
|
||||
* replacement2 = "_____";
|
||||
|
||||
char* result1 = str_replace(str, substr, replacement1, -1),
|
||||
* result2 = str_replace(str, substr, replacement2, 1);
|
||||
|
||||
puts(result1); free(result1);
|
||||
puts(result2); free(result2);
|
||||
|
||||
return 0;
|
||||
}
|
||||
#endif
|
16
c-programming/strings/str_replace.h
Normal file
16
c-programming/strings/str_replace.h
Normal file
@ -0,0 +1,16 @@
|
||||
/*
|
||||
* str_replace.h
|
||||
*
|
||||
* Author: Intel A80486DX2-66
|
||||
* License: Creative Commons Zero 1.0 Universal
|
||||
*/
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
char* str_replace(
|
||||
const char* str,
|
||||
const char* substr,
|
||||
const char* replacement,
|
||||
ssize_t max_count
|
||||
);
|
Loading…
Reference in New Issue
Block a user