Reputation: 196
If I have a string as follows: "Dragonballs are cool."
but I want to change the spaces into multiple lines: "---"
So this would be the end result: Dragonballs---are---cool.
How would i do it? Is a loop necessary (I know how to replace single characters with another single character), or is there another way to it?
Upvotes: 1
Views: 977
Reputation: 3650
I made an example program you can examine if you like. The biggest problem you'll encounter when replacing sub-strings is that you may need more room than the original source string has. So normally you want to write the modified source string somewhere else. You can use useful functions like strncat
and strncmp
to work around situations where you have a destination buffer that could be smaller than the expanded source.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BUF_LEN 32
#define MIN(p,q) ((p) < (q) ? (p) : (q))
void replace (const char *src, char *buf, size_t buf_size, const char *pat, const char *rep) {
size_t pat_len = strlen(pat), rep_len = strlen(rep);
int inc, i = 0;
const char *p = NULL;
while (*src != '\0') {
// Here, if we detect a match, we set our copy pointer and increment size.
if (strncmp(src, pat, pat_len) == 0) {
inc = MIN(buf_size - i - 1, rep_len);
p = rep;
} else {
inc = MIN(buf_size - i - 1, 1);
p = src;
}
// If we ran out of room in the buffer, we break out of the loop here.
if (inc <= 0) break;
// Here we append the chosen buffer with the increment size. Then increment our indexes.
buf = strncat(buf, p, inc);
i += inc;
++src;
}
// Don't forget the null-character.
buf[i] = '\0';
}
int main (void) {
const char *src = "Hello World!";
const char *match = " ";
const char *repl = "...";
char buf[MAX_BUF_LEN] = {0};
replace(src, buf, MAX_BUF_LEN, match, repl);
fprintf(stdout, "The string \"%s\" has been transformed to \"%s\"\n", src, buf);
return EXIT_SUCCESS;
}
Upvotes: 1
Reputation: 213711
There are several ways it can be done. One way is to tokenize the string first, to find out where the spaces are, for example by using strtok
.
Then copy the different sub strings (words) one by one into a new string (character array), for example with strcat
. For each string you copy, also copy a string "---"
.
The alternative is to just do all this manually without calling any string library functions.
Yes, you will need loops.
Upvotes: 6