0

Let the following example code:

char s1[] = "Hey there #!";
char s2[] = "Lou";

I would like to write a function which replaces the '#' with the value of s2. Also it allocates memory dynamically for a new output string which has the new replaced version. Is it possible in an elegant and non-complicated way, using mostly built-in functions? I'm aware of how to replace characters with a character in a string or strings with a given substring but this one seems to beat me.

3 Answers3

1

You will have to go through severall functions, but... here goes:

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
    char s1[] = "Hey there #!";
    char s2[] = "Lou";

    // Get the resulting length: s1, plus s2,
    // plus terminator, minus one replaced character
    // (the last two cancelling each other out).
    char * s3 = malloc( strlen( s1 ) + strlen( s2 ) );

    // The number of characters of s1 that are not "#".
    // This does search for "any character from the second
    // *string*", so "#", not '#'.
    size_t pos = strcspn( s1, "#" );

    // Copy up to '#' from s1
    strncpy( s3, s1, pos );

    // Append s2
    strcat( s3, s2 );

    // Append from s1 after the '#'
    strcat( s3, s1 + pos + 1 );

    // Check result.
    puts( s3 );
}

This isn't as efficient as you could make it (especially the multiple strcat() calls are inefficient), but it uses only standard functions in the most "simple" way, and doesn't do any "pointering" itself.

DevSolar
  • 67,862
  • 21
  • 134
  • 209
0

Check this out https://stackoverflow.com/a/32496721/5326843 According to this there is no standard function to replace a string. You have to write your own.

Surajit Mondal
  • 182
  • 2
  • 8
  • Yep, I know, but this is not what I want my desired output to be. I would like to replace a character in a string, with an another string, not with an another character. –  Dec 07 '18 at 15:55
  • Can't you just modifiy that function? – Surajit Mondal Dec 07 '18 at 16:31
0

There is no single libc call, but possible with the use of multiple libc calls, something like below, no need of dynamic allocation.

    #include <stdio.h>
    #include <string.h>
    char* replace_string(char* str, char* find, char* replace_str)
    {
        int len  = strlen(str);
        int len_find = strlen(find), len_replace = strlen(replace_str);
        for (char* ptr = str; ptr = strstr(ptr, find); ++ptr) {
            if (len_find != len_replace) 
                memmove(ptr+len_replace, ptr+len_find,
                    len - (ptr - str) + len_replace);
            memcpy(ptr, replace_str, len_replace);
        }
        return str;
    }

    int main(void)
    {
        char str[] = "Hey there #!";
        char str_replace[] = "Lou";
        printf("%s\n", replace_string(str, "#", str_replace));
        return 0;
    }

output :

Hey there Lou!
ntshetty
  • 1,293
  • 9
  • 20