Stripping characters from a string

Posted by Saerataga on Fri 03 Mar 2023 11:03 PM — 3 posts, 9,653 views.

#0
Hi

Anyone know what I'm doing wrong here?
I thought this would work to remove any of these characters from a string.


char     *strip_char(const char *str)
{
        static char ret[MSL];
        char     *retptr;

        retptr = ret;
        for (; *str != '\0'; str++)
        {
          if(*str == '(' || *str == ')' || *str == '<' || *str == '>' || *str == '=' || *str == '-' || *str == '*')
            continue;
                else
                {
                        *retptr = *str;
                        retptr++;
                }
        }
        *retptr = '\0';
        return ret;
}


[EDIT] Code tags added.
Amended on Sat 04 Mar 2023 12:30 AM by Nick Gammon
Australia Forum Administrator #1
Your code does work. I tested it stand-alone thus:


#include <stdio.h>

#define MSL 500

char     *strip_char(const char *str)
{
        static char ret[MSL];
        char     *retptr;

        retptr = ret;
        for (; *str != '\0'; str++)
        {
          if(*str == '(' || *str == ')' || *str == '<' || *str == '>' || *str == '=' || *str == '-' || *str == '*')
            continue;
                else
                {
                        *retptr = *str;
                        retptr++;
                }
        }
        *retptr = '\0';
        return ret;
}

int main ()
  {
  char test [] = "This is a test (round) less: < greater: > equals: = minus: - asterisk: * done";
  printf ("%s\n", strip_char (test));
  return 0;
  }


Compile and run:


$ gcc main.c
$ ./a.out



Output:


This is a test round less:  greater:  equals:  minus:  asterisk:  done


If it appears to be not working, the problem is in the way you are using it.
Amended on Sat 04 Mar 2023 01:51 AM by Nick Gammon
#2
Ok thanks for checking, I'll double check my placement.