Reputation: 25
I have to make a function which replaces each word (x), with another word(y), in a given text(**string). Can I replace them directly in the given text? Or should I make a new array and make the replacements there? However and don't know how to continue. The code I wrote is:
void operation_2(char x[100], char y[100], char **string, int N)
{
int len = 0;
char *word;
char s[12] = " .,?!\"';:";
char **newstring = (char **)malloc(N * sizeof(char *));
for (i = 0; i<= N; i++) {
word = strtok(string[i], s);
while (word != NULL) {
if (strcmp(word, x) == 0) {
len = strlen(string[i]) - strlen(x) + strlen(y);
newstring[i] = (char *)malloc((len + 1) * sizeof(char));
Upvotes: 0
Views: 106
Reputation: 60058
If you create a new string, it'll be able to take any string (string literal, an array on the stack, a static array, an array on the heap) as input, but it won't be as memory efficient.
If you want maximum memory efficiency, then you can modify the target string in-place, but you'll have restrictions depending on where the input string is stored.
realloc
it (shrink it or expand it)The memmove
function might come in handy if you decide to modify the string in place.
Keep in mind however, that:
strtok
Upvotes: 1