0

I wrote the below code which replaces '|' characters from the string.

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

void remove_pipes(char*);

main (int argc, char **argv)
{

char string1[] = "|||||||||||||";
remove_pipes(string1);
printf("String1 = %s", string1);
char string2[] = "h|e|l|l|o";
remove_pipes(string2);
printf("String2 = %s", string2);
}

void remove_pipes(char* input)
{
  for(; *input; input++)
  {
      if(*input == '|')
      {
          *input = ' ';
      }
  }
}

Now I need to modify this method to remove the '|' character from the string. I am not sure how to do that. Hope someone can give me some hint.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
  • 2
    Yes, it's pretty possible it is an homework. – jlliagre Dec 21 '11 at 08:04
  • Wow!! so much for removing pipe from a string. Simple `sed 's/|//g'` would have done the trick for you. – jaypal singh Dec 21 '11 at 08:07
  • Looks like some text editor should work for OP: both to prove possibility of the task and to actually perform the task :). – Alexei Levenkov Dec 21 '11 at 08:08
  • @jlliagre - I am not asking for code solution here, the code above i did from scratch based on some of the previous posting in stack overflow. I am just asking a hint. Since this variable is a pointer, how do I remove a character, that is where I am stuck. Could I just initialize another variable and append the non '|' values and reassign the variable content to char* input? – Nanthini Muniapan Dec 21 '11 at 08:09
  • @JaypalSingh - Right now I need this to be implemented in c program. This is a small chunk of a bigger program. This program will read content of xml file and check whether there are any '|' characters present and remove it. – Nanthini Muniapan Dec 21 '11 at 08:11
  • Look at http://stackoverflow.com/questions/779875/what-is-the-function-to-replace-string-in-c. – Vadzim Dec 21 '11 at 08:15
  • 1
    A hint: You can't just *delete* characters from a string. Given a string `"ab|cd"`, to change it to `"abcd"`, you need ``c`` in the position formerly occupied by ``|``, ``d`` in the position formerly occupied by `'c'`, and a terminating `'\0'` in the position formerly occupied by `'d'`. – Keith Thompson Dec 21 '11 at 10:02

1 Answers1

4

Use a char pointer to travel the input and modify it:

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

void remove_pipes(char*);

main (int argc, char **argv)
{

    char string1[] = "|||||||||||||";
    printf("String1 = %s\n", string1);
    remove_pipes(string1);
    printf("String1 = %s\n", string1);
    char string2[] = "h|e|l|l|o";
    printf("String2 = %s\n", string2);
    remove_pipes(string2);
    printf("String2 = %s\n", string2);
}

void remove_pipes(char* input)
{
    unsigned idx = 0;
    char* aux = input;

    for(; *input; input++)
    {
        if (*input != '|')
        {
            *(aux + idx++) = *input;
        }
    }
    *(aux + idx) = '\0';
}
Tio Pepe
  • 3,071
  • 1
  • 17
  • 22