Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. How can I extract numbers from string using basic::string? (STL)

How can I extract numbers from string using basic::string? (STL)

Scheduled Pinned Locked Moved C / C++ / MFC
questionc++sharepointdockerhelp
7 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • R Offline
    R Offline
    Ryan Park
    wrote on last edited by
    #1

    Hi, I'm a newbie to STL and have been on this stuff for all day long, but failed to implement. Plz help! ---My Situation goes--- Say, there is a string like "SP_CALL(~1,~123,~09,455,21)". I want to extract numbers after '~' character and store it to some container. Some like MAP, LIST, ...anything that could be used to restore extracted numbers for later comparison with other numbers. I've tried with very basic knowledge of STL, but maybe I'm lack much knowledge. So..If anyone can show some sample code fragments that implements this, or can point me to similar code, plz help me. Also, if there are any good books about STL for beginners, let me know. Thanks a million. Regards, Ryan :)

    C G 2 Replies Last reply
    0
    • R Ryan Park

      Hi, I'm a newbie to STL and have been on this stuff for all day long, but failed to implement. Plz help! ---My Situation goes--- Say, there is a string like "SP_CALL(~1,~123,~09,455,21)". I want to extract numbers after '~' character and store it to some container. Some like MAP, LIST, ...anything that could be used to restore extracted numbers for later comparison with other numbers. I've tried with very basic knowledge of STL, but maybe I'm lack much knowledge. So..If anyone can show some sample code fragments that implements this, or can point me to similar code, plz help me. Also, if there are any good books about STL for beginners, let me know. Thanks a million. Regards, Ryan :)

      C Offline
      C Offline
      Chris Losinger
      wrote on last edited by
      #2

      if you want to stick with STL, take a look at std::string and its member functions (especially substr, find* and c_str). the std::find* functions can help you isolate chunks of characters between commas and std::string::substr will let you extract those chunks. then use something like atoi to convert those chunks to numbers. this is one of those things where you have to make a loop that searches, extracts and converts. here's a small sample that might help:

      #include <string>
      std::string str = "SP_CALL(~1,~123,~09,455,21)";

      int iLeftParen = str.find_first_of('(');
      int iCommaPos = str.find(',', iLeftParen);

      // this is now "~1"
      std::string firstChunk = str.substr(iLeftParen, iCommaPos - (iLeftParen + 1));

      -c


      Smaller Animals Software, Inc. http://www.smalleranimals.com

      R R 2 Replies Last reply
      0
      • C Chris Losinger

        if you want to stick with STL, take a look at std::string and its member functions (especially substr, find* and c_str). the std::find* functions can help you isolate chunks of characters between commas and std::string::substr will let you extract those chunks. then use something like atoi to convert those chunks to numbers. this is one of those things where you have to make a loop that searches, extracts and converts. here's a small sample that might help:

        #include <string>
        std::string str = "SP_CALL(~1,~123,~09,455,21)";

        int iLeftParen = str.find_first_of('(');
        int iCommaPos = str.find(',', iLeftParen);

        // this is now "~1"
        std::string firstChunk = str.substr(iLeftParen, iCommaPos - (iLeftParen + 1));

        -c


        Smaller Animals Software, Inc. http://www.smalleranimals.com

        R Offline
        R Offline
        Rashid Thadha
        wrote on last edited by
        #3

        why don't you use strtok to get the delimitted numbers ? probably easier !!

        L 1 Reply Last reply
        0
        • R Rashid Thadha

          why don't you use strtok to get the delimitted numbers ? probably easier !!

          L Offline
          L Offline
          Lost User
          wrote on last edited by
          #4

          he asked how to do it with STL, not with strtok. -c

          1 Reply Last reply
          0
          • R Ryan Park

            Hi, I'm a newbie to STL and have been on this stuff for all day long, but failed to implement. Plz help! ---My Situation goes--- Say, there is a string like "SP_CALL(~1,~123,~09,455,21)". I want to extract numbers after '~' character and store it to some container. Some like MAP, LIST, ...anything that could be used to restore extracted numbers for later comparison with other numbers. I've tried with very basic knowledge of STL, but maybe I'm lack much knowledge. So..If anyone can show some sample code fragments that implements this, or can point me to similar code, plz help me. Also, if there are any good books about STL for beginners, let me know. Thanks a million. Regards, Ryan :)

            G Offline
            G Offline
            George Anescu
            wrote on last edited by
            #5

            The problem you are posing is very interesting: how to tokenize a string with the set of delimiter characters given in another string. I am giving a solution below. I implemented a more general function template to solve this kind of problems: <class Pred> void Tokenize(/*...*/) where you implement your delimiting criteria in a predicate class. When the set of delimiter characters are given in another string use the predicate CIsFromString(). After you get your strings in a vector container you can check your other ctiteria, like being a number after '~' the first character. I also give the function IsNumber() to check if a string is a number. Maybe all this solution deserves a separate article, I will think about it. The code (functions and a full testing program) is given bellow. It should compile without any problems with VC++. Good luck! #pragma warning(disable:4786) #include <algorithm> #include <functional> #include <iostream> #include <string> #include <vector> #include <locale> using namespace std; //For the case the default is a space. //This is the default predicate for the Tokenize() function. class CIsSpace : public unary_function<char, bool> { public: bool operator()(char c) const { //isspace<char> returns true if c is a white-space character (0x09-0x0D or 0x20) return isspace<char>(c); } }; //For the case the separator is a comma class CIsComma : public unary_function<char, bool> { public: bool operator()(char c) const { return (',' == c); } }; //For the case the separator is a character from a set of characters given in a string class CIsFromString : public unary_function<char, bool> { public: //Constructor specifying the separators CIsFromString(string const& rostr) : m_ostr(rostr) {} bool operator()(char c) const { int iFind = m_ostr.find(c); if(iFind != string::npos) return true; else return false; } private: string m_ostr; }; //Takes a string and a predicate, and tokenizes the string according to the separators which are //defined by the provided predicate. The predicate should evaluate to true when applied to a separator. template <class Pred> void Tokenize(string const& rostr, Pred const& roPred, vector<string>& roResult) { //First clear the results vector roResult.clear(); string::const_iterator it = rostr.begin(); string::const_iterator itTokenEnd = rostr.begin();

            R 1 Reply Last reply
            0
            • G George Anescu

              The problem you are posing is very interesting: how to tokenize a string with the set of delimiter characters given in another string. I am giving a solution below. I implemented a more general function template to solve this kind of problems: <class Pred> void Tokenize(/*...*/) where you implement your delimiting criteria in a predicate class. When the set of delimiter characters are given in another string use the predicate CIsFromString(). After you get your strings in a vector container you can check your other ctiteria, like being a number after '~' the first character. I also give the function IsNumber() to check if a string is a number. Maybe all this solution deserves a separate article, I will think about it. The code (functions and a full testing program) is given bellow. It should compile without any problems with VC++. Good luck! #pragma warning(disable:4786) #include <algorithm> #include <functional> #include <iostream> #include <string> #include <vector> #include <locale> using namespace std; //For the case the default is a space. //This is the default predicate for the Tokenize() function. class CIsSpace : public unary_function<char, bool> { public: bool operator()(char c) const { //isspace<char> returns true if c is a white-space character (0x09-0x0D or 0x20) return isspace<char>(c); } }; //For the case the separator is a comma class CIsComma : public unary_function<char, bool> { public: bool operator()(char c) const { return (',' == c); } }; //For the case the separator is a character from a set of characters given in a string class CIsFromString : public unary_function<char, bool> { public: //Constructor specifying the separators CIsFromString(string const& rostr) : m_ostr(rostr) {} bool operator()(char c) const { int iFind = m_ostr.find(c); if(iFind != string::npos) return true; else return false; } private: string m_ostr; }; //Takes a string and a predicate, and tokenizes the string according to the separators which are //defined by the provided predicate. The predicate should evaluate to true when applied to a separator. template <class Pred> void Tokenize(string const& rostr, Pred const& roPred, vector<string>& roResult) { //First clear the results vector roResult.clear(); string::const_iterator it = rostr.begin(); string::const_iterator itTokenEnd = rostr.begin();

              R Offline
              R Offline
              Ryan Park
              wrote on last edited by
              #6

              Hi, I didn't test or look into your code, but I thought that I should thank you first. Thank you very much for kind instruction. :-) I expected a simple fragment of sample code or pointing to similar code, but you surprised me. Thanks again for your time on this code and I guess this would be very helpful to those have problems with string manipulation with STL. Regards, Ryan :cool:

              1 Reply Last reply
              0
              • C Chris Losinger

                if you want to stick with STL, take a look at std::string and its member functions (especially substr, find* and c_str). the std::find* functions can help you isolate chunks of characters between commas and std::string::substr will let you extract those chunks. then use something like atoi to convert those chunks to numbers. this is one of those things where you have to make a loop that searches, extracts and converts. here's a small sample that might help:

                #include <string>
                std::string str = "SP_CALL(~1,~123,~09,455,21)";

                int iLeftParen = str.find_first_of('(');
                int iCommaPos = str.find(',', iLeftParen);

                // this is now "~1"
                std::string firstChunk = str.substr(iLeftParen, iCommaPos - (iLeftParen + 1));

                -c


                Smaller Animals Software, Inc. http://www.smalleranimals.com

                R Offline
                R Offline
                Ryan Park
                wrote on last edited by
                #7

                Hi, Thanks for your code. :-) Regards, Ryan

                1 Reply Last reply
                0
                Reply
                • Reply as topic
                Log in to reply
                • Oldest to Newest
                • Newest to Oldest
                • Most Votes


                • Login

                • Don't have an account? Register

                • Login or register to search.
                • First post
                  Last post
                0
                • Categories
                • Recent
                • Tags
                • Popular
                • World
                • Users
                • Groups