Solved

modifying a string

Posted on 2004-10-22
228 Views
Last Modified: 2010-04-01
Hello,
  I am trying to strip all the slashes in the string "am\\nbe\\rit&\\nb\\ngy&" . can somebody send me an algorithm for that
0
Question by:anshuma
    13 Comments
     
    LVL 20

    Assisted Solution

    by:ikework
    look at this:

    void StripBackslashes( char *pszDest, const char *pszSource );

    int main(int argc, char* argv[])
    {
          const char *pszSource = "abc\\def\\gh";
          char pszDestination[ 100 ];

          StripBackslashes( pszDestination, pszSource );

          printf( "source: '%s'\n", pszSource );
          printf( "dest  : '%s'\n", pszDestination );

          return 0;
    }

    void StripBackslashes( char *pszDest, const char *pszSource )
    {
          while( *pszSource )
          {
                if( *pszSource != '\\' )
                {
                      *pszDest++ = *pszSource;
                }
                ++pszSource;
          }
          *pszDest = '\0';
    }



    hope it helps ;)

    good luck, ike

    0
     
    LVL 20

    Expert Comment

    by:ikework
    be sure to include this:

    #include <stdio.h>
    0
     

    Author Comment

    by:anshuma
    I need to keep the string same ok

    x1="\abcd\game\a\s\d"

    stripslash(x1);

    x1="abcdgameasd"
    0
     

    Assisted Solution

    by:Codealot
    This does the trick:

    void removeChar( char c, char* s )
    {
          char* p = 0;
          while( p = strchr( s, c ) )
                memcpy( p, p+1, strlen(p+1)+1 );
    }

    int main(int argc, char **argv)
    {
      char t[] = ("am\\nbe\\rit&\\nb\\ngy&");
      removeChar( '\\', t );
      printf( t );

      return 0;
    }
    0
     
    LVL 20

    Expert Comment

    by:ikework
    is possible, but too much copy-overhead, you would have to replace the following chars with its
    previous one's after each removed char, lots of copy, the more efficient way is to allocate
    a buffer, like the above code does and copy the result to the original buffer, it could be done in the
    function like this:




    #include <stdio.h>
    #include <string.h>

    void StripBackslashes( char *pszValue );

    int main(int argc, char* argv[])
    {
          char pszStrip[ 100 ];
          strcpy( pszStrip, "am\\v" );

          StripBackslashes( pszStrip );

          printf( "stripped: '%s'\n", pszStrip );

          return 0;
    }

    void StripBackslashes( char *const pszStrip )
    {
          int intLen = strlen( pszStrip );
          if( !intLen ) return;

          char *pszBuffer = new char[ intLen + 1 ];

          char *pszSource = pszStrip;
          char *pszDest = pszBuffer;
                
          while( *pszSource )
          {
                if( *pszSource != '\\' )
                {
                      *pszDest++ = *pszSource;
                }
                ++pszSource;
          }
          *pszDest = '\0';

          strcpy( pszStrip, pszBuffer );

          delete[] pszBuffer;
    }

    0
     

    Accepted Solution

    by:
    Here is a nice little bit of code that will do the stripping out in place. It will perform nice and fast as its just basic pointer manipulation:

        // the string we want to strip
        char s[] = "am\\nbe\\rit&\\nb\\ngy&";

        // a read pointer and a write pointer
        char* readPtr = s;
        char* writePtr = s;

        // loop until we reach the null at the end of the string
        while (*readPtr)
        {
            // if the character is not a backslash we can add it to the string
            if (*readPtr != '\\')
            {
               *writePtr = *readPtr;
               writePtr++;
            }
           
            // move on to process the next character
            readPtr++;
        }
    0
     
    LVL 20

    Expert Comment

    by:ikework
    Codealot, this looks quite nice, but there are lots of hidden loops in your solution,
    strchr loops for each found char from the beginning of the string, lets say 4 slashes are
    found, 4 times the string will be looped through, and memcpy copies the whole stuff
    4 times, so if you are working with long strings, there's a really big overhead compared
    to the one-loop and one-copy solution
    0
     
    LVL 20

    Expert Comment

    by:ikework
    oh yeah, that's it, i guess xv has the best solution, since its one loop and
    no additional copy
    0
     

    Expert Comment

    by:Codealot
    @xv1700: Your solution net's "ngy&" in writePtr and an empty string in readPtr?

    @ikework: You won't always know the length of your input string - so char pszStrip[ 100 ] won't always suffice. To solve that you need to allocate on the heap, and take care of cleaning up afterwards, or do dynamic allocation (perf. penalty there too), either way you'd have to do more code. If performance is an issue, than it might be worth it, otherwise keeping it simple might be better?
    0
     

    Expert Comment

    by:Codealot
    @xv - sorry about that - wasn't paying attention to 's' - good solution!
    0
     
    LVL 20

    Expert Comment

    by:ikework
    @codealot: in xv's solution the readptr points to the end of the string s, because it looped through it,
    the 2 pointers are only little helpers, which modify the source string itsself, the string s[] holds the source
    and the result too, you need to look at this string, the result is there, that's the big benefit of his/her solution
    nothing needs to be copied...
    to my solution:
    >> To solve that you need to allocate on the heap, and take care of cleaning up afterwards
    i did that in my second suggestion, but anyway your right with the allocation/deallocation - performance
    problem, but it doesn't worth talking about it, since it's not the best solution, as xv teached us...

    btw, performance is always an issue, isn't it ;)
    0
     

    Expert Comment

    by:xv1700
    Thanks guys, that was my first post - I now feel empowered to move on to the more complex.
    0
     

    Expert Comment

    by:xv1700
    I just realised that I forgot to null terminate the string after shrinking it:

    // the string we are going to modify in place
        char s[] = "am\\nbe\\rit&\\nb\\ngy&";

        // temporary pointers for string manipulation
        char* readPtr = s;
        char* writePtr = s;

        // loop round the whole string
        while (*readPtr)
        {
            // if its a backslash then skip it
            // otherwise add it back on to our string
            if (*readPtr != '\\')
            {
               *writePtr = *readPtr;

               // move on our write pointer
               writePtr++;
            }

            // move on to read the next byte
            readPtr++;
        }

        // ensure the string is null terminated as it may have shrunk
        *writePtr = '\0';
    0

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
    What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
    The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
    The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…

    884 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

    Need Help in Real-Time?

    Connect with top rated Experts

    18 Experts available now in Live!

    Get 1:1 Help Now