HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Given a string, print another one without a given char

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withoutchargivenoneprintanotherstring

Problem

My aim is to write a C program (I must create a function) that, given a string and a character, returns another string without the given char value.

For example: function("Hello World!", 'l'); / Prints "Heo Word!" /

So I've programmed a lot with Java and I am used to programming but I am not used to C and in particular to pointers. I managed to do it with a single difference, this is the code:

#include 

#define STR_LEN 32

char *stringChop(char *s1, char *s2, char c);

int main() {
    char string[STR_LEN - 1] = "Esame di fondamenti";
    char stringChopped[STR_LEN - 1];
    stringChop(string, stringChopped, 'm');
    printf("%s\n\n", stringChopped);
    return 0;
}

char *stringChop(char *s1, char *s2, char c) {
    char *p = s1;
    char *q = s2;
    while (p < &s1[STR_LEN]) {
        if (*p != c) {
            *q = *p;
            p++;
            q++;
        } else {
            p++;
        }
    }
    return s2;
}


As you can see, in the function stringChop I've put 2 strings because I didn't know how to return one, so instead I used a pointer to one string initialised in the main() function and edited it with the use of pointers.
Now, my question is: How can I achieve the same thing with a function that accepts only one string and only a char value?

Solution

Passing strings and buffers in C is a pain. For this problem, it would be idiomatic to write a function that accepts an in-out parameter — basically a mutable string. It works well in this case because you know that the result will never be longer than the original string.

char *deleteChars(char *s, char c) {
    char *out = s;
    for (char *in = s; *in; in++) {
        if (*in != c) {
            *out++ = *in;
        }
    }
    *out = '\0';
    return s;
}


If the caller wants to obtain the result as a separate string, then let the caller duplicate the string before calling deleteChars().

Code Snippets

char *deleteChars(char *s, char c) {
    char *out = s;
    for (char *in = s; *in; in++) {
        if (*in != c) {
            *out++ = *in;
        }
    }
    *out = '\0';
    return s;
}

Context

StackExchange Code Review Q#111738, answer score: 2

Revisions (0)

No revisions yet.