function replace substring returns incorrect answer

Becker

I have a program replacing a substring in a string. The idea is to find the string_to_be_replaced in original_string, then realloc the new_string and connect it to replace_by string. It works for some cases but in some cases like below, it return wrong answer:

Input:

abc def ghi //orginal string

(a blank space) //string to be replaced

1234 //replace by

Output:

abc1234defT123ghi

Expected output:

abc1234def1234ghi

When I debug it, I saw a wrong character has been filled in the new_string after the first replacement had been done.

Please tell me why does this happen and how to fix it. Any help would be appreciated.

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

void fgetsWithoutNewline(char *s, size_t maxCount, FILE *fp);
bool sameString(char *original_tring, char *string_to_be_searched, size_t start);
char *replaceString(char *original_tring, char *string_to_be_replaced, char *replace_by);

int main()
{
    char *original_string = malloc(100);
    fgetsWithoutNewline(original_string, 99, stdin);

    char *string_to_be_replaced = malloc(100);
    fgetsWithoutNewline(string_to_be_replaced, 99, stdin);

    char *replace_by = malloc(100);
    fgetsWithoutNewline(replace_by, 99, stdin);

    char *s = replaceString(original_string, string_to_be_replaced, replace_by);
    printf("%s", s);

    free(original_string);
    free(string_to_be_replaced);
    free(replace_by);
    return 0;
}

void fgetsWithoutNewline(char *s, size_t maxCount, FILE *fp)
{
    if (fgets(s, maxCount, fp))
    {
        s[strcspn(s, "\n")] = '\0';
    }
    return;
}

char *replaceString(char *original_tring, char *string_to_be_replaced, char *replace_by)
{
    if (!original_tring || !string_to_be_replaced || !replace_by)
    {
        return NULL;
    }
    char *new_string = malloc(strlen(original_tring));

    for (size_t i = 0, j = 0; i < strlen(original_tring); i++, j++)
    {
        if (sameString(original_tring, string_to_be_replaced, i))
        {
            new_string = realloc(new_string, strlen(new_string) + strlen(replace_by) - strlen(string_to_be_replaced));
            strcat(new_string, replace_by);
            i += strlen(string_to_be_replaced) - 1;  // i and j use to track the last character of original string and new string
            j += strlen(replace_by) - 1;
        }
        else
        {
            new_string[j] = original_tring[i];
        }
    }
    return new_string;
}

bool sameString(char *original_tring, char *string_to_be_searched, size_t start)
{
    if (strlen(string_to_be_searched) + start > strlen(original_tring))
    {
        return false;
    }
    size_t end = strlen(string_to_be_searched) + start;
    for (size_t i = start, j = 0; i < end; i++, j++)
    {
        if (original_tring[i] != string_to_be_searched[j])
        {
            return false;
        }
    }
    return true;
}
anastaciu

Well the symptoms are clear, the string is not being null terminated.

Try the follwing:

Live demo

char *replaceString(char *original_tring, char *string_to_be_replaced, const char *replace_by)
{
    if (!original_tring || !string_to_be_replaced || !replace_by)
    {
        return NULL;
    }
    char *new_string = malloc(strlen(original_tring));

    for (size_t i = 0, j = 0; i < strlen(original_tring); i++, j++)
    {
        if (sameString(original_tring, string_to_be_replaced, i))
        {
            new_string = realloc(new_string, strlen(new_string) + strlen(replace_by) - strlen(string_to_be_replaced));
            strcat(new_string, replace_by);
            i += strlen(string_to_be_replaced) - 1;
            j += strlen(replace_by) - 1;
        }
        else
        {
            new_string[j] = original_tring[i];
        }
        new_string[j + 1] = '\0'; //here
    }  
    return new_string;
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Answer from Function is incorrect

sympy dsolve returns incorrect answer

WorksheetFunction.Average returns incorrect answer

Calendar TimeZone inDaylightTime returns incorrect answer for Israel

Len function returns incorrect results

Python function returns incorrect value

checkPrime function returns incorrect values

Substring function in C with malloc returning incorrect value

numpy.piecewise returns incorrect answer when using lambda

JS function logs answer but returns "undefined"

Function to replace a substring with a function value in javascript

Why does the date format function return incorrect answer?

Custom Loss Function of Keras Model Giving Incorrect Answer

Trying to set ProcessStrictHandleCheckPolicy returns 87 - Incorrect Function

PL/pgSQL function returns incorrect bitwise result

JQuery function returns incorrect amount of pixels

PHP rsort function returns incorrect ordering

Function returns incorrect False (only at higher values)

Array formula with SUM Function returns incorrect result

Why does this query function returns incorrect results?

Split a substring that returns from a split function

specifics replace substring in string with php function

C returns incorrect float value after function returns

Expression returning incorrect answer

Python incorrect answer input

Program returns incorrect answer and "-nan(ind)". What did I do wrong?

function in queen's Attack II returns wrong answer

Javascript | Recursive function I created returns undefined along with the proper answer

Returns different answer when using else return to top of function command

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    pump.io port in URL

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  14. 14

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  15. 15

    How to use merge windows unallocated space into Ubuntu using GParted?

  16. 16

    flutter: dropdown item programmatically unselect problem

  17. 17

    Pandas - check if dataframe has negative value in any column

  18. 18

    Nuget add packages gives access denied errors

  19. 19

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  20. 20

    Generate random UUIDv4 with Elm

  21. 21

    Client secret not provided in request error with Keycloak

HotTag

Archive