3
\$\begingroup\$

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 <stdio.h>

#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?

\$\endgroup\$
2
\$\begingroup\$

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().

\$\endgroup\$
4
  • \$\begingroup\$ So you set 2 pointers to the same string basically and then as you go through it you edit it, right? \$\endgroup\$ – Matt Nov 24 '15 at 21:12
  • \$\begingroup\$ Yes, it copies the wanted characters from the string to itself. \$\endgroup\$ – 200_success Nov 24 '15 at 21:13
  • \$\begingroup\$ Allright, thanks for the tip! What about declaring a new string in the function and declare it static? So it would stay fresh in the memory and later in the main() function I'll be able to do something like char string[] = function(...) \$\endgroup\$ – Matt Nov 24 '15 at 21:15
  • \$\begingroup\$ No, don't use a static variable there. You'll get all kinds of incorrect behaviour if the function is called multiple times. \$\endgroup\$ – 200_success Nov 24 '15 at 21:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.