Replace a ; with a string

I am trying to write a function that takes a string called line, looks for and removes any semicolons in the line, and replaces it with the string "LINE-END". Any help would be appreciated because I have been trying for hours and I am stumped.

Comments

  • Post your attempts then, so we don't have to guess where the problem is, but rather point it out to you.

    There are two ways to write this function:

    - Leave the old string unchanged and make a re-formatted copy of it. (probably the best way in most cases)

    - Edit the old string. Much more complicated and requires that the old string is large enough to contain the changes. It doesn't make sense to use this method unless you have very little RAM in your system, ie you are programming some sort of embedded device and not a PC.

    Also concider whether or not you wish the program to use dynamic memory allocation. In case you choose to use it, I would advise to write the program like this:

    [code]
    /* main */

    char str[] = "BLABLA;";
    char* new_str;
    int alloc_size;

    alloc_size = getSizeToAllocate(str); /* function that counts ';' and multiplies
    their number with strlen("LINE_END"), to get the needed length of the string */

    new_str = malloc(alloc_size);

    formatString(str, new_str);

    ...
    free(new_str);
    [/code]

    This way you end up with two functions, one that calculates how much memory you should allocate, and one that does the actual work. The advantage of this is that you leave memory allocation to the caller, ie main(). When using dynamic memory allocation, it is usually bad practice to let functions allocate the memory, because that is an almost certain way to end up with memory leaks.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion