C++ strings and strchr()

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • ataru@nospam.cyberspace.org

    C++ strings and strchr()

    I want to find the position of a character in a string and replace it another
    if it is actually there, and I'd like the operation to be efficient. I'm
    assuming the "standard" way to do this is something like

    string s = "blah";
    int i = s.find_first_of ('a'); /* returns 2, I presume? */
    s.replace(i,0," e");

    Right? Is this the best way (assuming I haven't made some stupid error)? Is
    there a way to (easily!) get a character pointer from a C++ string so I can
    just change that one character, like maybe

    char *cp;

    if( (cp=strchr(s.c_ str(), 'a') != NULL)
    *cp='e';

    ? If neither way is good, what's a better way?

    (if this is a FAQ, I didn't see it...)

    --
    Christopher Benson-Manica | Jumonji giri, for honour.
    ataru(at)cybers pace.org |
  • Ron Natalie

    #2
    Re: C++ strings and strchr()


    <ataru@nospam.c yberspace.org> wrote in message news:bi2uab$o8g $1@chessie.cirr .com...
    [color=blue]
    > string s = "blah";[/color]
    [color=blue]
    > int i = s.find_first_of ('a'); /* returns 2, I presume? */[/color]

    You need to check to see if the find succeeds (unless you are sure it won't fail).
    It might return npos. You could also use s.find('a'). Since your match string is
    only a single character they both do the same thing (I'm not sure that one would
    be faster than the other).
    [color=blue]
    > s.replace(i,0," e");[/color]

    That's a no op. It says to replace zero chars. You want.
    s.replace(i, 1, "e");
    Actually, for a single character this would be just as good
    s[i] = 'e';



    Comment

    • ataru@nospam.cyberspace.org

      #3
      Re: C++ strings and strchr()

      Ron Natalie <ron@sensor.com > broke the eternal silence and spoke thus:
      [color=blue]
      > Actually, for a single character this would be just as good
      > s[i] = 'e';[/color]

      You can reference strings as though they were C-style char*'s?


      --
      Christopher Benson-Manica | Jumonji giri, for honour.
      ataru(at)cybers pace.org |

      Comment

      • Agent Mulder

        #4
        Re: C++ strings and strchr()

        ataru@nospam.cy berspace.org:[color=blue]
        > I want to find the position of a character in a string and replace it[/color]
        another[color=blue]
        > if it is actually there, and I'd like the operation to be efficient. I'm
        > assuming the "standard" way to do this is something like
        >
        > string s = "blah";
        > int i = s.find_first_of ('a'); /* returns 2, I presume? */
        > s.replace(i,0," e");[/color]

        #include<algori thm>
        replace(s.begin (),s.end(),'a', 'e');

        -X


        Comment

        • Mike Wahler

          #5
          Re: C++ strings and strchr()


          <ataru@nospam.c yberspace.org> wrote in message
          news:bi2vmn$o8t $1@chessie.cirr .com...[color=blue]
          > Ron Natalie <ron@sensor.com > broke the eternal silence and spoke thus:
          >[color=green]
          > > Actually, for a single character this would be just as good
          > > s[i] = 'e';[/color]
          >
          > You can reference strings as though they were C-style char*'s?[/color]

          Not entirely. E.g. 'strlen()' et al won't necessarily work
          as you expect. But std::string does feature 'index'
          operators '[]'. It also has other 'intuitive' operators,
          such as '+' for concatenation.

          Which C++ book(s) are you reading?

          -Mike



          Comment

          • Mike Wahler

            #6
            Re: C++ strings and strchr()


            Agent Mulder <mbmulder_remov e_this_@home.nl > wrote in message
            news:bi30l0$nf1 $1@news2.tilbu1 .nb.home.nl...[color=blue]
            > ataru@nospam.cy berspace.org:[color=green]
            > > I want to find the position of a character in a string and replace it[/color]
            > another[color=green]
            > > if it is actually there, and I'd like the operation to be efficient.[/color][/color]
            I'm[color=blue][color=green]
            > > assuming the "standard" way to do this is something like
            > >
            > > string s = "blah";
            > > int i = s.find_first_of ('a'); /* returns 2, I presume? */
            > > s.replace(i,0," e");[/color]
            >
            > #include<algori thm>
            > replace(s.begin (),s.end(),'a', 'e');[/color]

            Nearly all C++ literature I've read states that one
            should usually prefer a member function over a 'free'
            function, if it does what you need. This is because
            a member function could be optimized to take advantage
            of internal details not available to 'free' functions.

            In OP's case, I'd use 'std::string::f ind()' followed
            by access to the found element with 'std::string::o perator[]()'.

            $.02,
            -Mike



            Comment

            • Agent Mulder

              #7
              Re: C++ strings and strchr()

              MW> Nearly all C++ literature I've read states that one
              MW> should usually prefer a member function over a 'free'
              MW> function, if it does what you need. This is because
              MW> a member function could be optimized to take advantage
              MW> of internal details not available to 'free' functions.

              You produced some very ugly code, Mike ;-)7

              <mikes>
              #include <iostream>
              #include <string>

              int main()
              {
              his();
              std::string s("blah");
              std::cout << s << '\n';
              std::string::si ze_type i(s.find('a'));

              if(i != std::string::np os)
              s[i] = 'e';

              std::cout << s << '\n';

              return 0;
              }
              </mikes>

              -X




              Comment

              • Ron Natalie

                #8
                Re: C++ strings and strchr()


                <ataru@nospam.c yberspace.org> wrote in message news:bi2vmn$o8t $1@chessie.cirr .com...[color=blue]
                > Ron Natalie <ron@sensor.com > broke the eternal silence and spoke thus:
                >[color=green]
                > > Actually, for a single character this would be just as good
                > > s[i] = 'e';[/color]
                >
                > You can reference strings as though they were C-style char*'s?[/color]

                Well, not totally, but they do support operator[] as shown above.


                Comment

                • ataru@nospam.cyberspace.org

                  #9
                  Re: C++ strings and strchr()

                  Mike Wahler <mkwahler@mkwah ler.net> broke the eternal silence and spoke thus:
                  [color=blue]
                  > Which C++ book(s) are you reading?[/color]

                  "The C++ Programming Language" by Stroustrup (aka God?) - it's in there, but
                  the book is so big I overlooked it... sorry... but I do have a question
                  about how they're implemented. Why can't you effectively modify the char*
                  that c_str gives you? Wouldn't that make one's life easier?

                  --
                  Christopher Benson-Manica | Jumonji giri, for honour.
                  ataru(at)cybers pace.org |

                  Comment

                  • ataru@nospam.cyberspace.org

                    #10
                    Re: C++ strings and strchr()

                    Mike Wahler <mkwahler@mkwah ler.net> broke the eternal silence and spoke thus:
                    [color=blue]
                    > Which C++ book(s) are you reading?[/color]

                    "The C++ Programming Language" by Stroustrup (aka God?) - it's in there, but
                    the book is so big I overlooked it... sorry... but I do have a question
                    about how they're implemented. Why can't you effectively modify the char*
                    that c_str gives you? Wouldn't that make one's life easier when dealing with
                    C-style string functions?

                    --
                    Christopher Benson-Manica | Jumonji giri, for honour.
                    ataru(at)cybers pace.org |

                    Comment

                    • Bob Jacobs

                      #11
                      Re: C++ strings and strchr()


                      "Mike Wahler" <mkwahler@mkwah ler.net> wrote in message
                      news:l881b.1969 $Ej6.1248@newsr ead4.news.pas.e arthlink.net...[color=blue]
                      >
                      > Agent Mulder <mbmulder_remov e_this_@home.nl > wrote in message
                      > news:bi30l0$nf1 $1@news2.tilbu1 .nb.home.nl...[color=green]
                      > > ataru@nospam.cy berspace.org:[color=darkred]
                      > > > I want to find the position of a character in a string and replace it[/color]
                      > > another[color=darkred]
                      > > > if it is actually there, and I'd like the operation to be efficient.[/color][/color]
                      > I'm[color=green][color=darkred]
                      > > > assuming the "standard" way to do this is something like
                      > > >
                      > > > string s = "blah";
                      > > > int i = s.find_first_of ('a'); /* returns 2, I presume? */
                      > > > s.replace(i,0," e");[/color]
                      > >
                      > > #include<algori thm>
                      > > replace(s.begin (),s.end(),'a', 'e');[/color]
                      >
                      > Nearly all C++ literature I've read states that one
                      > should usually prefer a member function over a 'free'
                      > function, if it does what you need. This is because
                      > a member function could be optimized to take advantage
                      > of internal details not available to 'free' functions.
                      >
                      > In OP's case, I'd use 'std::string::f ind()' followed
                      > by access to the found element with 'std::string::o perator[]()'.[/color]

                      It would be useful to know the OP's intention here, as the two examples
                      aren't completely equivalent. One is intended to replace the first occurence
                      of 'a' with 'e' whilst the other will replace all instances of 'a' with 'e'.
                      For "blah" the effect is the same, of course.



                      Comment

                      • Mike Wahler

                        #12
                        Re: C++ strings and strchr()


                        Agent Mulder <mbmulder_remov e_this_@home.nl > wrote in message
                        news:bi3347$82h $1@news2.tilbu1 .nb.home.nl...[color=blue]
                        > MW> Nearly all C++ literature I've read states that one
                        > MW> should usually prefer a member function over a 'free'
                        > MW> function, if it does what you need. This is because
                        > MW> a member function could be optimized to take advantage
                        > MW> of internal details not available to 'free' functions.
                        >
                        > You produced some very ugly code, Mike ;-)7[/color]

                        Why do you find it 'ugly'? What would you do instead
                        that you'd consider less 'ugly'?

                        -Mike



                        Comment

                        • ataru@nospam.cyberspace.org

                          #13
                          Re: C++ strings and strchr()

                          Bob Jacobs <news05@robertj acobs.fsnet.co. uk> broke the eternal silence and spoke thus:
                          [color=blue]
                          > It would be useful to know the OP's intention here, as the two examples
                          > aren't completely equivalent. One is intended to replace the first occurence
                          > of 'a' with 'e' whilst the other will replace all instances of 'a' with 'e'.
                          > For "blah" the effect is the same, of course.[/color]

                          My original (flawed!) intention was actually to replace a single character in
                          a string with a null terminator (a la C - guess what I took in college? ;)),
                          which of course wouldn't have worked... And then I realized that the strings
                          I wanted already existed in the code anyway, so the whole exercise was
                          pointless... but at least I learned something.

                          --
                          Christopher Benson-Manica | Jumonji giri, for honour.
                          ataru(at)cybers pace.org |

                          Comment

                          • Mike Wahler

                            #14
                            Re: C++ strings and strchr()


                            <ataru@nospam.c yberspace.org> wrote in message
                            news:bi33hk$oik $2@chessie.cirr .com...[color=blue]
                            > Mike Wahler <mkwahler@mkwah ler.net> broke the eternal silence and spoke[/color]
                            thus:[color=blue]
                            >[color=green]
                            > > Which C++ book(s) are you reading?[/color]
                            >
                            > "The C++ Programming Language" by Stroustrup (aka God?) - it's in there,[/color]
                            but[color=blue]
                            > the book is so big I overlooked it... sorry... but I do have a question
                            > about how they're implemented. Why can't you effectively modify the char*
                            > that c_str gives you? Wouldn't that make one's life easier when dealing[/color]
                            with[color=blue]
                            > C-style string functions?[/color]

                            Why do you want to use those functions with std::string's?

                            AFAIK, std::string supports anything you can do with a 'C-style
                            string', and more, in a much safer way.

                            -Mike
                            [color=blue]
                            >
                            > --
                            > Christopher Benson-Manica | Jumonji giri, for honour.
                            > ataru(at)cybers pace.org |[/color]


                            Comment

                            • Thomas Matthews

                              #15
                              Re: C++ strings and strchr()

                              ataru@nospam.cy berspace.org wrote:[color=blue]
                              > Ron Natalie <ron@sensor.com > broke the eternal silence and spoke thus:
                              >
                              >[color=green]
                              >>Actually, for a single character this would be just as good
                              >> s[i] = 'e';[/color]
                              >
                              >
                              > You can reference strings as though they were C-style char*'s?
                              >
                              >[/color]

                              You can't access the string directly as C-style char*'s,
                              but you _can_ access a copy that is a C-style string.
                              Look up the "c_str()" method:
                              string b("blah");
                              cout << strlen(b.c_str( ));

                              The std::string class has many of the functions that
                              are used on C-style strings. Look through the list
                              of std::string methods.

                              --
                              Thomas Matthews

                              C++ newsgroup welcome message:

                              C++ Faq: http://www.parashift.com/c++-faq-lite
                              C Faq: http://www.eskimo.com/~scs/c-faq/top.html
                              alt.comp.lang.l earn.c-c++ faq:

                              Other sites:
                              http://www.josuttis.com -- C++ STL Library book

                              Comment

                              Working...