replace substring

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • magix

    replace substring

    Hi,

    I have
    char* str1 = "d:\temp\data\t est.txt"

    I want to replace all the "\" to be "\\", so that

    the string will have "d:\\temp\\data \\test.txt"

    Can you help ?

    Regards,
    Magix

  • James Dow Allen

    #2
    Re: replace substring

    On May 26, 2:06 pm, magix <mag...@gmail.c omwrote:
    I want to replace all the "\" to be "\\", so that
    Try
    sed ss\\\\s\\\\\\\\ sg

    YMMV

    James Dow Allen

    Comment

    • Richard Heathfield

      #3
      Re: replace substring

      magix said:
      Hi,
      >
      I have
      char* str1 = "d:\temp\data\t est.txt"
      If you have that, you're in trouble, because \d isn't a valid escape
      sequence. \t is, but I don't think you really wanted embedded tabs in that
      string, did you?
      I want to replace all the "\" to be "\\", so that
      >
      the string will have "d:\\temp\\data \\test.txt"
      >
      Can you help ?
      char *str1 = "d:\\temp\\data \\test.txt";

      If that doesn't fix your problem, you need to clarify what your problem is.

      --
      Richard Heathfield <http://www.cpax.org.uk >
      Email: -http://www. +rjh@
      Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
      "Usenet is a strange place" - dmr 29 July 1999

      Comment

      • Martin Ambuhl

        #4
        Re: replace substring

        magix wrote:
        Hi,
        >
        I have
        char* str1 = "d:\temp\data\t est.txt"
        >
        I want to replace all the "\" to be "\\", so that
        >
        the string will have "d:\\temp\\data \\test.txt"
        >
        Can you help ?
        The string to which str1 points is a string literal, and you should not
        attempt to modify it. String literals are usually not modifiable and in
        any case your new string takes more space than the string literal does,
        so even if you could modify it, you would overrun the end of it.

        You need to allocate an array of sufficient space for the new string
        (including the terminating zero-byte) and then something like

        /* warning: neither tested nor written to be bulletproof
        (or even dart-resistant) */
        void replaceslash(ch ar *source, char *target)
        {
        for (;*source; source++)
        {
        if (*source = '\\') *target++ = *source;
        *target++ = *source;
        }
        }

        Now, the code above simply produces two '\\' when it sees one.
        But on almost any system, it makes more sense to replace '\\' with '/'
        (even windows and dos have no problem with this), when the above
        then becomes
        void replaceslash(ch ar *source, char *target)
        {
        for (;*source; source++)
        {
        if (*source = '\\') *target++ = '/';
        else *target++ = *source; /* notice the else! */
        }
        }

        Comment

        • Szabolcs Borsanyi

          #5
          Re: replace substring

          On Mon, May 26, 2008 at 12:29:05AM -0700, James Dow Allen wrote:
          On May 26, 2:06 pm, magix <mag...@gmail.c omwrote:
          I want to replace all the "\" to be "\\", so that
          >
          Try
          sed ss\\\\s\\\\\\\\ sg
          This sed solution seems to be off-topic, but, when applied to the OP's
          source, could fix the C problem.

          The OP should tell how he got that invalid string literal. If it his
          own typing, he should replace the backslashes with pairs of backslashes,
          either by hand or using the sed script above. (But it is unlikely to have
          sed on a platform with path names containing lot's of backslashes.)

          (you=OP)
          On the other hand, it is an interesting question, how to replace
          valid backslash characters in a string to pairs of backslashes, which can
          be relevant, e.g. when writing a source code or passing the string to an
          other picky application. If that is the case, you can do this replacement
          on the course of copying each character to a separate character array.

          Third point is, that it is possible to put a string into a character
          array , like char path[]="d:\\path"; This character array cannot hold
          more characters than it did originally, but feel free to put a big number
          between the square brackets so that you do not have this limitation.
          (This point is surely covered by the faq)

          Szabolcs
          >
          YMMV
          >
          James Dow Allen

          Comment

          • Bartc

            #6
            Re: replace substring


            "magix" <magix8@gmail.c omwrote in message
            news:debb18bd-c54b-4446-b60f-fc675d2e1aa2@p2 5g2000pri.googl egroups.com...
            Hi,
            >
            I have
            char* str1 = "d:\temp\data\t est.txt"
            >
            I want to replace all the "\" to be "\\", so that
            >
            the string will have "d:\\temp\\data \\test.txt"
            >
            Can you help ?
            If str1 really contains those slashes, then it already represents a valid
            Windows filename, if that was the idea.

            Doubling up the slashes I think still yields a valid filename, but is
            unnecessary.

            But if that is initialisation code from a C program, the slashes will be
            converted or ignored.

            Assuming however you do have such a string and want to double up the
            slashes, I tried this somewhat fiddly code. You may want to put str1=str2 at
            the end, but is anyway just to give an idea. Note the double \\ characters
            here are really single.


            /* Duplicate \ characters in a string */
            #include <stdio.h>
            #include <stdlib.h>
            #include <string.h>

            int main(void)
            {
            char* str1 = "d:\\temp\\data \\test.txt"; /* old string (in const memory)
            */
            char* str2 = NULL; /* new string (to be in heap memory) */
            char *p,*q;
            char c;
            int i,len,slashes;

            slashes=0;
            len=strlen(str1 );

            for (i=0; i<len; ++i) /* Calculate size of new string */
            if (str1[i]=='\\')++slashe s;

            str2=malloc(len +slashes+1);

            if (str2!=NULL) {
            p=str1;
            q=str2;
            while (c=*p++) {
            *q++ = c;
            if (c=='\\') *q++ = '\\';
            };
            *q++ = 0;
            printf("STR1 = %s\n",str1);
            printf("STR2 = %s\n",str2);

            // free(str2);
            }
            else
            puts("No memory");

            }



            Comment

            • Keith Thompson

              #7
              Re: replace substring

              magix <magix8@gmail.c omwrites:
              I have
              char* str1 = "d:\temp\data\t est.txt"
              >
              I want to replace all the "\" to be "\\", so that
              >
              the string will have "d:\\temp\\data \\test.txt"
              >
              Can you help ?
              You're going to need to be clearer about what you have and what you
              want.

              Do you mean that you have a declaration:

              const char* str1 = "d:\temp\data\t est.txt";

              (note: I added the "const" and the semicolon) *in a C source file*,
              and you want to modify the C source file so the declaration is

              const char* str1 = "d:\\temp\\data \\test.txt";

              ? If so, I'd say the best tool for the job is a text editor; just add
              the extra backslashes and save the file. But that's so trivial that I
              suspect it's not really what you were asking.

              If you want to modify a large number of such incorrect declarations,
              it's going to be difficult. For one thing, backslashes can appear
              legitimately in string literals; you wouldn't want to change
              "hello, world\n"
              to
              "hello, world\\n"
              .. I can imagine ways to detect which string literals should be
              translated and which should be left alone, but it can't be done 100%
              reliably, and I wouldn't even make the attempt without a lot more
              information.

              If you mean that you want to leave the declaration alone and change
              the value of the string at run time, you're pretty much out of luck
              (and fixing the declaration is a much better idea anyway).

              Tell us what you're really trying to do, and we can probably help.

              --
              Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
              Nokia
              "We must do something. This is something. Therefore, we must do this."
              -- Antony Jay and Jonathan Lynn, "Yes Minister"

              Comment

              • CBFalconer

                #8
                Re: replace substring

                magix wrote:
                >
                I have
                char* str1 = "d:\temp\data\t est.txt"
                >
                I want to replace all the "\" to be "\\", so that
                the string will have "d:\\temp\\data \\test.txt"
                >
                Can you help ?
                No. str1 is a non-writable string. You can create str2 and copy
                str1, with modifications, into it. The copy part will look
                something like:

                while (*p1) {
                if ('\' == (*p2++ = *p1++)) *p2++ = '\';
                }

                --
                [mail]: Chuck F (cbfalconer at maineline dot net)
                [page]: <http://cbfalconer.home .att.net>
                Try the download section.

                ** Posted from http://www.teranews.com **

                Comment

                • Antoninus Twink

                  #9
                  Re: replace substring

                  On 26 May 2008 at 7:32, CBFalconer wrote:
                  The copy part will look something like:
                  >
                  while (*p1) {
                  if ('\' == (*p2++ = *p1++)) *p2++ = '\';
                  }
                  It won't look like that if you want it to pass a code review in any
                  professional environment. Blech.

                  Comment

                  • Richard

                    #10
                    Re: replace substring

                    CBFalconer <cbfalconer@yah oo.comwrites:
                    magix wrote:
                    >>
                    >I have
                    > char* str1 = "d:\temp\data\t est.txt"
                    >>
                    >I want to replace all the "\" to be "\\", so that
                    >the string will have "d:\\temp\\data \\test.txt"
                    >>
                    >Can you help ?
                    >
                    No. str1 is a non-writable string. You can create str2 and copy
                    str1, with modifications, into it. The copy part will look
                    something like:
                    >
                    while (*p1) {
                    if ('\' == (*p2++ = *p1++)) *p2++ = '\';
                    }
                    Note to magix : never, ever lay your code out like this or it will be
                    laughed out of any code review. Multiple statements on line might save a
                    little bit vertical real estate but are a pain in the behind to debug
                    and read. Others might disagree. Only you can decide.

                    Something like (not compiled or tested but you get the meaning I hope)

                    char c;
                    while (c = *d++ = *s++) { /* s==source, d==destination */
                    if (c=='\')
                    *d++ = '\';
                    }

                    Comment

                    • Ben Bacarisse

                      #11
                      Re: replace substring

                      Richard<rgrdev@ gmail.comwrites :
                      CBFalconer <cbfalconer@yah oo.comwrites:
                      >
                      >magix wrote:
                      <a question about doubling \s>
                      >>Can you help ?
                      <snip>
                      > while (*p1) {
                      > if ('\' == (*p2++ = *p1++)) *p2++ = '\';
                      > }
                      >
                      Note to magix : never, ever lay your code out like this or it will be
                      laughed out of any code review. Multiple statements on line might save a
                      little bit vertical real estate but are a pain in the behind to debug
                      and read. Others might disagree. Only you can decide.
                      >
                      Something like (not compiled or tested but you get the meaning I hope)
                      >
                      char c;
                      while (c = *d++ = *s++) { /* s==source, d==destination */
                      if (c=='\')
                      *d++ = '\';
                      }
                      The layout is up to you, of course, but you've altered the semantics.

                      --
                      Ben.

                      Comment

                      • Richard Harter

                        #12
                        Re: replace substring

                        On Fri, 30 May 2008 16:48:42 +0200, Richard<rgrdev@ gmail.com>
                        wrote:
                        >CBFalconer <cbfalconer@yah oo.comwrites:
                        >
                        >magix wrote:
                        >>>
                        >>I have
                        >> char* str1 = "d:\temp\data\t est.txt"
                        >>>
                        >>I want to replace all the "\" to be "\\", so that
                        >>the string will have "d:\\temp\\data \\test.txt"
                        >>>
                        >>Can you help ?
                        >>
                        >No. str1 is a non-writable string. You can create str2 and copy
                        >str1, with modifications, into it. The copy part will look
                        >something like:
                        >>
                        > while (*p1) {
                        > if ('\' == (*p2++ = *p1++)) *p2++ = '\';
                        > }
                        >
                        >Note to magix : never, ever lay your code out like this or it will be
                        >laughed out of any code review. Multiple statements on line might save a
                        >little bit vertical real estate but are a pain in the behind to debug
                        >and read. Others might disagree. Only you can decide.
                        >
                        >Something like (not compiled or tested but you get the meaning I hope)
                        >
                        char c;
                        while (c = *d++ = *s++) { /* s==source, d==destination */
                        if (c=='\')
                        *d++ = '\';
                        }
                        >
                        Obscene noises and horselaughs. I doubt that I would
                        intentionally hire anyone who objected to CFB's code, which uses
                        standard C idioms. More strongly, in my opinion anyone who has
                        difficulty reading it or debugging probably has made a bad career
                        choice.

                        Note that CFB's code does not have multiple statements on one
                        line.

                        Also I do not like your suggested alternative. Let me count the
                        ways. YMMV of course.

                        Introducing c is problematic. In C89 it will need to be at the
                        beginning of the block in which the loop is contained breaking
                        the connection between the declaration and the code that uses it.
                        More importantly it is a bit of obfuscation.

                        I don't like the multiple assignment trick (c = *d++ = *s++).
                        Count that as a personal prejudice.

                        The lines
                        if (c=='\')
                        *d++ = '\';
                        are a definite style error. Either write

                        if (c=='\') *d++ = '\';

                        making it clear that the if controls a single statement, or

                        if (c=='\') {
                        *d++ = '\';
                        }

                        The trouble with the format that you used is that it is fragile;
                        it is easy to erroneously add another statement to what appears
                        to be a block. If you do, the code compiles and the error can be
                        surprisingly hard to find.









                        Richard Harter, cri@tiac.net
                        http://home.tiac.net/~cri, http://www.varinoma.com
                        Save the Earth now!!
                        It's the only planet with chocolate.

                        Comment

                        • Keith Thompson

                          #13
                          Re: replace substring

                          CBFalconer <cbfalconer@yah oo.comwrites:
                          magix wrote:
                          >>
                          >I have
                          > char* str1 = "d:\temp\data\t est.txt"
                          >>
                          >I want to replace all the "\" to be "\\", so that
                          >the string will have "d:\\temp\\data \\test.txt"
                          >>
                          >Can you help ?
                          >
                          No. str1 is a non-writable string. You can create str2 and copy
                          str1, with modifications, into it. The copy part will look
                          something like:
                          >
                          while (*p1) {
                          if ('\' == (*p2++ = *p1++)) *p2++ = '\';
                          }
                          Note that '\' is a syntax error. It should be '\\'.

                          --
                          Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
                          Nokia
                          "We must do something. This is something. Therefore, we must do this."
                          -- Antony Jay and Jonathan Lynn, "Yes Minister"

                          Comment

                          • Keith Thompson

                            #14
                            Re: replace substring

                            cri@tiac.net (Richard Harter) writes:
                            On Fri, 30 May 2008 16:48:42 +0200, Richard<rgrdev@ gmail.com>
                            wrote:
                            >
                            >>CBFalconer <cbfalconer@yah oo.comwrites:
                            [...]
                            >> while (*p1) {
                            >> if ('\' == (*p2++ = *p1++)) *p2++ = '\';
                            >> }
                            >>
                            >>Note to magix : never, ever lay your code out like this or it will be
                            >>laughed out of any code review. Multiple statements on line might save a
                            >>little bit vertical real estate but are a pain in the behind to debug
                            >>and read. Others might disagree. Only you can decide.
                            [...]
                            Note that CFB's code does not have multiple statements on one
                            line.
                            Yes, it does. It just happens that one of the statements is part of
                            the other statement.

                            (Assuming, of course, that '\' is changed to '\\'.)

                            --
                            Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
                            Nokia
                            "We must do something. This is something. Therefore, we must do this."
                            -- Antony Jay and Jonathan Lynn, "Yes Minister"

                            Comment

                            • rio

                              #15
                              Re: replace substring


                              "CBFalconer " <cbfalconer@yah oo.comha scritto nel messaggio
                              news:483A677F.9 50DC227@yahoo.c om...
                              magix wrote:
                              >>
                              >I have
                              > char* str1 = "d:\temp\data\t est.txt"
                              >>
                              >I want to replace all the "\" to be "\\", so that
                              >the string will have "d:\\temp\\data \\test.txt"
                              >>
                              >Can you help ?
                              >
                              No. str1 is a non-writable string. You can create str2 and copy
                              str1, with modifications, into it. The copy part will look
                              something like:
                              while (*p1) {
                              if ('\' == (*p2++ = *p1++)) *p2++ = '\';
                              }
                              here there should be
                              *p2=0;

                              so "if ('\' == (*p2++ = *p1++)) *p2++ = '\';"
                              should be
                              c=*p2 = *p1; ++p1; ++p2;
                              if(c=='\') *p2++ = '\';




                              Comment

                              Working...