Remove backslash from string in c

Posted on 2015-01-30
Last Modified: 2015-02-14
I need c code to remove backslash from a string.
For example, the string is "abcdef\ghijklmn", I need to remove \ from string and get the other characters to another string as "abcdefghijklmn".
Please help with the c code.

Question by:Manoj Dasaraju
LVL 45

Assisted Solution

by:Kent Olsen
Kent Olsen earned 100 total points
ID: 40581029
Hi Manoj,

You'll have to do the work yourself.  :(  But it's not a bad task.  Just find the backslash, and copy the string to the right of it back 1 character (over the backslash).  Repeat if you need to remove all of the backslashes.

char *s1 = "abcdef\ghijklmn";
char *s2;
char *p;

  s2 = strdup (s1);   //  Make a copy of the original.
  p = strchr (s2, '\\');
  while (p)
    strcpy (p, p+1);
    p = strchr (s2, '\\');  //  Check for another backslash.

// This leaves the edited string in s2.

Good Luck,
LVL 19

Accepted Solution

simon3270 earned 400 total points
ID: 40590851
Alternatively, you can do it in-place with:

        char s[] = "abcdef\\ghij";
        char *p1, *p2;
        p1 = p2 = s;

        printf("Before  %s\n", s);
        while (*p1) {
                if ((*p1) != '\\') {
                        *p2 = *p1;
        *p2 = 0;
        printf("After  %s\n", s);

Open in new window

I've doubled up the backslashes - a single \ in a string would treat the character after as a special character (e.g. "\t" would be a single tab character).

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.

685 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question