need help with string

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

    need help with string

    let's say have a string: string str="arg1 arg2 arg3";

    I need to convert it to

    char **s where s={arg1, arg2,arg3, NULL};


    has anyone encountered this problem and has fast solution?

    Thanks

  • Vimal Aravindashan

    #2
    Re: need help with string

    puzzlecracker wrote:[color=blue]
    > let's say have a string: string str="arg1 arg2 arg3";
    >
    > I need to convert it to
    >
    > char **s where s={arg1, arg2,arg3, NULL};
    >
    >
    > has anyone encountered this problem and has fast solution?
    >
    > Thanks
    >[/color]

    If you have tried something to get it done, post your code, and you'll
    get help.
    If you are trying to get someone else to do your work, you are just
    another ... I'll reserve my comments. :-)

    Anyway, here's are a couple of tips.
    1) string's c_str() returns a non-modifiable C string, so use copy()
    instead.
    2) Replace the spaces with '\0' to "create" separate strings out of the
    copied string.

    Hope this helps...

    Rgds,
    Vimal.


    --
    "If you would be a real seeker after truth, it is necessary that at
    least once in your life you doubt, as far as possible, all things."
    -- Rene Descartes

    Comment

    • Someonekicked

      #3
      Re: need help with string

      most direct way ( there might be easier way),
      #include <iostream>

      #include <sstream>

      #include <string>



      using namespace std;

      int main()

      {

      string str="arg1 arg2 arg3";

      stringstream ss;

      char **s;

      int count_space = str.size() == 0 ? 0 : 1; // cover the case of empty
      string

      for(int i = 0; i < str.size(); i++)

      {

      if (str[i] == ' ')

      count_space++;

      }

      s = new char * [count_space + 1];

      s[count_space] = NULL;


      ss << str;

      for(int i = 0; ss >> str; i++)

      {

      s[i] = new char[str.length() + 1];

      strncpy(s[i],str.data(),str .length());

      s[i][str.length()] = '\0';

      }



      return 0;

      }

      "puzzlecrac ker" <ironsel2000@gm ail.com> wrote in message
      news:1129506388 .273665.259970@ g49g2000cwa.goo glegroups.com.. .[color=blue]
      > let's say have a string: string str="arg1 arg2 arg3";
      >
      > I need to convert it to
      >
      > char **s where s={arg1, arg2,arg3, NULL};
      >
      >
      > has anyone encountered this problem and has fast solution?
      >
      > Thanks
      >[/color]


      Comment

      • Mike Wahler

        #4
        Re: need help with string


        "puzzlecrac ker" <ironsel2000@gm ail.com> wrote in message
        news:1129506388 .273665.259970@ g49g2000cwa.goo glegroups.com.. .[color=blue]
        > let's say have a string: string str="arg1 arg2 arg3";
        >
        > I need to convert it to
        >
        > char **s where s={arg1, arg2,arg3, NULL};
        >
        >
        > has anyone encountered this problem and has fast solution?[/color]

        #include <iostream>
        #include <string.h>

        int main()
        {
        const char *data = "arg1 arg2 arg3";
        char *a[sizeof data / sizeof *data + 1] =
        {
        strstr(data, "arg1"),
        strstr(data, "arg2"),
        strstr(data, "arg3")
        };

        char **s = a;

        size_t i = 0;

        while(s[i])
        {
        for(size_t j = 0; j < 4; ++j)
        std::cout.put(s[i][j]);

        std::cout.put(' \n');
        ++i;
        }

        return 0;
        }

        This was the fastest way I could write it.

        ("Useful?", now that's a different story. :-))

        -Mike


        Comment

        • puzzlecracker

          #5
          Re: need help with string


          Vimal Aravindashan wrote:[color=blue]
          > puzzlecracker wrote:[color=green]
          > > let's say have a string: string str="arg1 arg2 arg3";
          > >
          > > I need to convert it to
          > >
          > > char **s where s={arg1, arg2,arg3, NULL};
          > >
          > >
          > > has anyone encountered this problem and has fast solution?
          > >
          > > Thanks
          > >[/color]
          >
          > If you have tried something to get it done, post your code, and you'll
          > get help.
          > If you are trying to get someone else to do your work, you are just
          > another ... I'll reserve my comments. :-)
          >
          > Anyway, here's are a couple of tips.
          > 1) string's c_str() returns a non-modifiable C string, so use copy()
          > instead.
          > 2) Replace the spaces with '\0' to "create" separate strings out of the
          > copied string.
          >
          > Hope this helps...
          >
          > Rgds,
          > Vimal.
          >
          >
          > --
          > "If you would be a real seeker after truth, it is necessary that at
          > least once in your life you doubt, as far as possible, all things."
          > -- Rene Descartes[/color]




          string args= "srcipt arg1 arg2 arg3..."
          .....

          int size=args.size( )*2; // to make sure I have enough room
          char *argvec=new char[size];
          memset(argvec,' \0',size);
          args.copy(argve c,size);

          pid_t pid;
          if(pid=fork()<0 )
          {
          cerr<<"failed in fork(), exit 1\n";
          exit(1);

          }
          else if(pid==0)
          {
          if(execv("/home/work/bin/script",&argvec )<0)
          {
          cerr<<"failed in execv, exit 1\n";
          exit(1);
          }
          }
          .....


          for some reason execv failed.. any ideas?

          ffaialed in execv, exit 1
          iled in execv, exit 1


          with

          Comment

          • puzzlecracker

            #6
            Re: need help with string


            Someonekicked wrote:[color=blue]
            > most direct way ( there might be easier way),
            > #include <iostream>
            >
            > #include <sstream>
            >
            > #include <string>
            >
            >
            >
            > using namespace std;
            >
            > int main()
            >
            > {
            >
            > string str="arg1 arg2 arg3";
            >
            > stringstream ss;
            >
            > char **s;
            >
            > int count_space = str.size() == 0 ? 0 : 1; // cover the case of empty
            > string
            >
            > for(int i = 0; i < str.size(); i++)
            >
            > {
            >
            > if (str[i] == ' ')
            >
            > count_space++;
            >
            > }
            >
            > s = new char * [count_space + 1];
            >
            > s[count_space] = NULL;
            >
            >
            > ss << str;
            >
            > for(int i = 0; ss >> str; i++)
            >
            > {
            >
            > s[i] = new char[str.length() + 1];
            >
            > strncpy(s[i],str.data(),str .length());
            >
            > s[i][str.length()] = '\0';
            >
            > }
            >
            >
            >
            > return 0;
            >
            > }[/color]
            Thanks, might not work, you forgetting issue about tabs

            Comment

            • Vimal Aravindashan

              #7
              Re: need help with string

              puzzlecracker wrote:[color=blue]
              > Vimal Aravindashan wrote:
              >[color=green]
              >>puzzlecrack er wrote:
              >>[color=darkred]
              >>>let's say have a string: string str="arg1 arg2 arg3";
              >>>
              >>>I need to convert it to
              >>>
              >>> char **s where s={arg1, arg2,arg3, NULL};
              >>>
              >>>[/color]
              >>Anyway, here's are a couple of tips.
              >>1) string's c_str() returns a non-modifiable C string, so use copy()
              >>instead.
              >>2) Replace the spaces with '\0' to "create" separate strings out of the
              >>copied string.
              >>[/color]
              >
              >
              > string args= "srcipt arg1 arg2 arg3..."
              > .....
              >
              > int size=args.size( )*2; // to make sure I have enough room[/color]
              No need. args.size() will do just fine.
              [color=blue]
              > char *argvec=new char[size];
              > memset(argvec,' \0',size);[/color]
              No need for this memset either.
              [color=blue]
              > args.copy(argve c,size);
              >[/color]
              Its okay till here. After you find out how many args are there (n), this
              is what you need to do:
              NOTE: following code was not tested, so use it more like pseudocode

              char **sz;
              sz = new (char *)[n+1]; // you need a NULL at the end, right?

              sz[0] = &argvec[0]; // sz[0] will hold only the first arg (you'll see)

              c = 1; // we already have the first arg

              for(int i=0; i<args.length() ; i++) {
              if(argvec[i]==' ') {
              sz[c++] = &argvec[i+1]; // the remaining args

              argvec[i] = '\0'; // replacing the space with '\0', makes each one
              separate.
              }
              }
              sz[c] = NULL; // the final NULL

              The remaining code has nothing to do with C++. Try a different newsgroup.


              Cheers,
              Vimal.
              [color=blue]
              > pid_t pid;
              > if(pid=fork()<0 )
              > {
              > cerr<<"failed in fork(), exit 1\n";
              > exit(1);
              >
              > }
              > else if(pid==0)
              > {
              > if(execv("/home/work/bin/script",&argvec )<0)
              > {
              > cerr<<"failed in execv, exit 1\n";
              > exit(1);
              > }
              > }
              > .....
              >
              >
              > for some reason execv failed.. any ideas?
              >
              > ffaialed in execv, exit 1
              > iled in execv, exit 1
              >
              >
              > with
              >[/color]


              --
              "If you would be a real seeker after truth, it is necessary that at
              least once in your life you doubt, as far as possible, all things."
              -- Rene Descartes

              Comment

              • Kai-Uwe Bux

                #8
                Re: need help with string

                puzzlecracker wrote:
                [color=blue]
                >
                > Someonekicked wrote:[color=green]
                >> most direct way ( there might be easier way),
                >> #include <iostream>
                >>
                >> #include <sstream>
                >>
                >> #include <string>
                >>
                >>
                >>
                >> using namespace std;
                >>
                >> int main()
                >>
                >> {
                >>
                >> string str="arg1 arg2 arg3";
                >>
                >> stringstream ss;
                >>
                >> char **s;
                >>
                >> int count_space = str.size() == 0 ? 0 : 1; // cover the case of empty
                >> string
                >>
                >> for(int i = 0; i < str.size(); i++)
                >>
                >> {
                >>
                >> if (str[i] == ' ')
                >>
                >> count_space++;
                >>
                >> }
                >>
                >> s = new char * [count_space + 1];
                >>
                >> s[count_space] = NULL;
                >>
                >>
                >> ss << str;
                >>
                >> for(int i = 0; ss >> str; i++)
                >>
                >> {
                >>
                >> s[i] = new char[str.length() + 1];
                >>
                >> strncpy(s[i],str.data(),str .length());
                >>
                >> s[i][str.length()] = '\0';
                >>
                >> }
                >>
                >>
                >>
                >> return 0;
                >>
                >> }[/color]
                > Thanks, might not work, you forgetting issue about tabs[/color]

                What about:

                #include <string>
                #include <vector>
                #include <sstream>
                #include <iostream>

                typedef char* c_string;
                typedef c_string* c_string_array;

                c_string to_c_string ( std::string const & str ) {
                // you own the result, you have to delete it.
                // use delete [] to get rid of that crap.
                c_string result = new char [ str.size() + 1 ];
                std::string::si ze_type i;
                for ( i = 0; i < str.size(); ++i ) {
                result[i] = str[i];
                }
                result[i] = 0;
                return( result );
                }

                c_string_array chop ( std::string const & str ) {
                // you own the result, you have to delete it.
                // use delete [] to get rid of that crap.
                // BEWARE: you have to get rid of the c_strings therein first.
                std::istringstr eam istr ( str );
                std::string arg;
                std::vector< c_string > dummy;
                while ( istr >> arg ) {
                dummy.push_back ( to_c_string( arg ) );
                }
                c_string_array result = new c_string [ dummy.size() + 1 ];
                std::vector< c_string >::size_type i;
                for ( i = 0; i < dummy.size(); ++i ) {
                result[i] = dummy[i];
                }
                result[i] = 0;
                return ( result );
                }

                int main ( void ) {
                std::string line ( "ab cd efg" );
                c_string_array arr = chop ( line );
                for ( c_string* str_ptr = arr; *str_ptr != 0; ++str_ptr ) {
                std::cout << *str_ptr << '\n';
                delete *str_ptr;
                }
                delete arr;
                }



                Best

                Kai-Uwe Bux

                Comment

                • Dave Townsend

                  #9
                  Re: need help with string


                  "puzzlecrac ker" <ironsel2000@gm ail.com> wrote in message
                  news:1129506388 .273665.259970@ g49g2000cwa.goo glegroups.com.. .[color=blue]
                  > let's say have a string: string str="arg1 arg2 arg3";
                  >
                  > I need to convert it to
                  >
                  > char **s where s={arg1, arg2,arg3, NULL};
                  >
                  >
                  > has anyone encountered this problem and has fast solution?
                  >
                  > Thanks
                  >[/color]

                  You've not been reading recent posts, redfloyd posted a similar solution
                  which
                  I've shamelessly adapted....Of course, you might use strtok() to token your
                  original
                  string & create the array of what-have-yous.

                  #include <string>
                  #include <sstream>
                  #include <iterator>
                  #include <vector>
                  int main(int argc, char* argv[])
                  {

                  char* ARGS[100];
                  int ARGSC = 0;

                  std::istringstr eam is(" arg1 arg2 arg3 arg4 arg5 " );
                  for ( std::istream_it erator<std::str ing> it(is) ;
                  it!=std::istrea m_iterator<std: :string>() ; ++it, ++ARGSC)
                  {
                  std::string s=*it;


                  ARGS[ARGSC]= strdup( s.c_str() );


                  }
                  return 0;

                  }


                  Comment

                  • puzzlecracker

                    #10
                    Re: need help with string


                    Dave Townsend wrote:[color=blue]
                    > "puzzlecrac ker" <ironsel2000@gm ail.com> wrote in message
                    > news:1129506388 .273665.259970@ g49g2000cwa.goo glegroups.com.. .[color=green]
                    > > let's say have a string: string str="arg1 arg2 arg3";
                    > >
                    > > I need to convert it to
                    > >
                    > > char **s where s={arg1, arg2,arg3, NULL};
                    > >
                    > >
                    > > has anyone encountered this problem and has fast solution?
                    > >
                    > > Thanks
                    > >[/color]
                    >
                    > You've not been reading recent posts, redfloyd posted a similar solution
                    > which
                    > I've shamelessly adapted....Of course, you might use strtok() to token your
                    > original
                    > string & create the array of what-have-yous.
                    >
                    > #include <string>
                    > #include <sstream>
                    > #include <iterator>
                    > #include <vector>
                    > int main(int argc, char* argv[])
                    > {
                    >
                    > char* ARGS[100];
                    > int ARGSC = 0;
                    >
                    > std::istringstr eam is(" arg1 arg2 arg3 arg4 arg5 " );
                    > for ( std::istream_it erator<std::str ing> it(is) ;
                    > it!=std::istrea m_iterator<std: :string>() ; ++it, ++ARGSC)
                    > {
                    > std::string s=*it;
                    >
                    >
                    > ARGS[ARGSC]= strdup( s.c_str() );
                    >
                    >
                    > }
                    > return 0;
                    >
                    > }[/color]


                    Almost all of your solutions expose a notorious problem in c++
                    community that has rather horrid and sadistic ramifications. That
                    problem is memory leak. Would anyone suggest a solution where we don't
                    have to deal with memory - at least directly to solve this problem?


                    Ps. I said'some' because they only need one for loop to solve it.


                    ps2. I hate mixing c and c++ - the task for fearless and
                    ready-to-explain-your-boss-why-component-fucks-up.

                    Comment

                    • Branimir Maksimovic

                      #11
                      Re: need help with string


                      "puzzlecrac ker" <ironsel2000@gm ail.com> wrote in message
                      news:1129512072 .807182.190920@ g44g2000cwa.goo glegroups.com.. .[color=blue]
                      >[color=green]
                      >> puzzlecracker wrote:[color=darkred]
                      >> > let's say have a string: string str="arg1 arg2 arg3";
                      >> >
                      >> > I need to convert it to
                      >> >
                      >> > char **s where s={arg1, arg2,arg3, NULL};
                      >> >
                      >> >
                      >> > has anyone encountered this problem and has fast solution?
                      >> >
                      >> > Thanks
                      >> >[/color]
                      >>[/color]
                      >
                      >
                      >
                      > string args= "srcipt arg1 arg2 arg3..."
                      > .....
                      >
                      > int size=args.size( )*2; // to make sure I have enough room
                      > char *argvec=new char[size];
                      > memset(argvec,' \0',size);
                      > args.copy(argve c,size);
                      >[/color]

                      vector<char*> argv;
                      string a ="script arg1 arg2 arg3";
                      vector<char> args(a.begin(), a.end());
                      args.push_back( ' ');
                      while(vector<ch ar>::iterator i=args.begin(), j=args.end();i! =args.end();)
                      {
                      vector<char>::i terator k = find(i,j,' ');
                      *k = 0;
                      argv.push_back( &*i);
                      i=++k;
                      }
                      argv.push_back( 0);
                      [color=blue]
                      > pid_t pid;
                      > if(pid=fork()<0 )
                      > {
                      > cerr<<"failed in fork(), exit 1\n";
                      > exit(1);
                      >
                      > }
                      > else if(pid==0)
                      > {
                      > if(execv("/home/work/bin/script",&argvec )<0)[/color]
                      if(execv("/home/work/bin/script",&argv[0])<0)[color=blue]
                      > {
                      > cerr<<"failed in execv, exit 1\n";
                      > exit(1);
                      > }
                      > }
                      > .....
                      >
                      >
                      > for some reason execv failed.. any ideas?[/color]
                      You didn't pass array of pointers to char.

                      Greetings, Bane.


                      Comment

                      • Branimir Maksimovic

                        #12
                        Re: need help with string


                        "Branimir Maksimovic" <bmaxa@eunet.yu > wrote in message
                        news:divdc6$ho4 $1@news.eunet.y u...[color=blue]
                        >
                        > while(vector<ch ar>::iterator i=args.begin(), j=args.end();i! =args.end();)[/color]

                        should be
                        for(vector<char >::iterator i=args.begin(), j=args.end();i! =args.end();)


                        Comment

                        • Dave Townsend

                          #13
                          Re: need help with string

                          The memory has to be allocated somewhere Sunshine, you'll have
                          to figure out how to release it when you're done. Alternatively, you
                          can restate your problem to use strings instead of char*.


                          "puzzlecrac ker" <ironsel2000@gm ail.com> wrote in message
                          news:1129519016 .895416.110390@ g47g2000cwa.goo glegroups.com.. .[color=blue]
                          >
                          > Dave Townsend wrote:[color=green]
                          > > "puzzlecrac ker" <ironsel2000@gm ail.com> wrote in message
                          > > news:1129506388 .273665.259970@ g49g2000cwa.goo glegroups.com.. .[color=darkred]
                          > > > let's say have a string: string str="arg1 arg2 arg3";
                          > > >
                          > > > I need to convert it to
                          > > >
                          > > > char **s where s={arg1, arg2,arg3, NULL};
                          > > >
                          > > >
                          > > > has anyone encountered this problem and has fast solution?
                          > > >
                          > > > Thanks
                          > > >[/color]
                          > >
                          > > You've not been reading recent posts, redfloyd posted a similar solution
                          > > which
                          > > I've shamelessly adapted....Of course, you might use strtok() to token[/color][/color]
                          your[color=blue][color=green]
                          > > original
                          > > string & create the array of what-have-yous.
                          > >
                          > > #include <string>
                          > > #include <sstream>
                          > > #include <iterator>
                          > > #include <vector>
                          > > int main(int argc, char* argv[])
                          > > {
                          > >
                          > > char* ARGS[100];
                          > > int ARGSC = 0;
                          > >
                          > > std::istringstr eam is(" arg1 arg2 arg3 arg4 arg5 " );
                          > > for ( std::istream_it erator<std::str ing> it(is) ;
                          > > it!=std::istrea m_iterator<std: :string>() ; ++it, ++ARGSC)
                          > > {
                          > > std::string s=*it;
                          > >
                          > >
                          > > ARGS[ARGSC]= strdup( s.c_str() );
                          > >
                          > >
                          > > }
                          > > return 0;
                          > >
                          > > }[/color]
                          >
                          >
                          > Almost all of your solutions expose a notorious problem in c++
                          > community that has rather horrid and sadistic ramifications. That
                          > problem is memory leak. Would anyone suggest a solution where we don't
                          > have to deal with memory - at least directly to solve this problem?
                          >
                          >
                          > Ps. I said'some' because they only need one for loop to solve it.
                          >
                          >
                          > ps2. I hate mixing c and c++ - the task for fearless and
                          > ready-to-explain-your-boss-why-component-fucks-up.
                          >[/color]






                          Comment

                          Working...