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 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

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.
Can't you just modifiy that function?
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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.