Very simple string help needed

This is a discussion on Very simple string help needed within the C++ Programming forums, part of the General Programming Boards category; I guess I have no choice but to give up. Thanks for trying. If most of us had that attitude ...

  1. #16
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,596
    I guess I have no choice but to give up. Thanks for trying.
    If most of us had that attitude we would have taken up something else long ago. Everyday we face complex and daunting problems and we don't have the liberty of just giving up. You should research into loops, string, and find().

  2. #17
    Registered User
    Join Date
    Dec 2009
    Posts
    120
    Quote Originally Posted by Bubba View Post
    You should research into loops, string, and find().
    That's the thing, I already know about those things. I have the book right in front of me. I have done plenty of programs involving loops. I also know how to use string and find(). For some reason I just do not know how to use a loop and find () to find out how many times a letter appears in a program.

  3. #18
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,596
    I will show you code that extracts values from a comma delimited string. This may help you. I use this in my SpaceX prototype to extract vectors from XML config files.

    Code:
    template <typename T> bool XMLUtils::ExtractValuesFromString(const std::string & text,const std::string & delim,T *pValues)
    {
        bool result = false;
        size_t pos = 0;
        size_t pos2 = text.find(delim,pos);
        int count = 0;
        std::string value;
    
        while (pos2 != std::string::npos)
        {
            result = true;   //Found at least 1 of the specified delimiters
            if (pos == 0)
            {
                value = text.substr(pos,(pos2 - pos));
            }
            else
            {
                value = text.substr(pos + 1,(pos2 - pos));
            }
    
            pValues[count] = static_cast<T>(atof(value.c_str()));
            ++count;
            pos = pos2;
            
            pos2 = text.find(delim,pos + 1);
        }
    
        size_t length = text.length();
        std::string last = text.substr(pos + 1,text.length() - (pos + 1));
        pValues[count] = static_cast<T>(atof(last.c_str()));
       
    
        return result;
    }
    Forgive the template code. It is there so that I can use the function for int, float and what have you. Pay attention to how I'm using find to find all the specified delimiters. Forget about the sub string extraction portion as well as the data type stuff.

    Here is some code that uses the function:
    Code:
    const D3DXCOLOR XMLUtils::ExtractColorFromString(const std::string &text)
    {
        D3DXCOLOR result = D3DXCOLOR(0.0f,0.0f,0.0f,0.0f);
    
        float values[4];
        if (ExtractValuesFromString<float>(text,",",values))
        {
           result = D3DXCOLOR(values[0],values[1],values[2],values[3]);
        }
        return result;
    }
    Last edited by VirtualAce; 02-13-2010 at 07:01 PM.

  4. #19
    Registered User
    Join Date
    Oct 2006
    Posts
    2,351
    Quote Originally Posted by Bubba View Post
    Here is some code that uses the function:
    Code:
    const D3DXCOLOR XMLUtils::ExtractColorFromString(const std::string &text)
    {
        D3DXCOLOR result = D3DXCOLOR(0.0f,0.0f,0.0f,0.0f);
    
        float values[4];
        if (ExtractValuesFromString<float>(text,",",values))
        {
           result = D3DXCOLOR(values[0],values[1],values[2],values[3]);
        }
        return result;
    }
    interestingly enough, while this is obviously intended to be an example, that code does an unnecessary copy when you say:
    Code:
    D3DXCOLOR result = D3DXCOLOR(0.0f,0.0f,0.0f,0.0f);
    when you could simply say:
    Code:
    D3DXCOLOR result(0.0f,0.0f,0.0f,0.0f);
    if this code is in a production system and is used inside an inner loop of some sort, you could potentially see significant performance gains by eliminating the copy of the object.

    in any case, the way I attack a problem I'm unsure about is to write down in human language what steps *I* would take if I were going to do it by hand. then I translate that into code, and it speeds up the process a lot.

  5. #20
    Registered User
    Join Date
    Oct 2006
    Location
    Canada
    Posts
    1,243
    Quote Originally Posted by Bubba
    You should research into loops, string, and find().
    Quote Originally Posted by nick753 View Post
    That's the thing, I already know about those things. I have the book right in front of me. I have done plenty of programs involving loops. I also know how to use string and find(). For some reason I just do not know how to use a loop and find () to find out how many times a letter appears in a program.
    Having a book in front of you really means nothing. Apparently you do not know "about those things", or "how to use string and find()". If you did, you could complete this task. Do not jump ahead to other topics without fully understanding the material and concepts before it. Don't write one "string" program, and move on. Learning is done by repetition. This is a fact. If you don't give sufficient practice to each topic, you will not learn that topic. You said you know how to use for loops, but in your code you posted a for loop that is not correct. Im not talking about its not the complete solution or not, Im saying its not what someone who "knows" how to write for loops would write (i.e. the semicolon you placed after the for loop--a logic error). Go back and read a tutorial on "for" loops. It is not possible to say that you cant find a great tutorial explaining exactly how they work, with examples.

    Dont take any of this personal or as an insult, its not intended to be so. We are all here to offer free help, for those who take the time to ask for it and for those who really want it. You said that you're learning this on your own, which is an impressive thing in its own right.

  6. #21
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,538
    Quote Originally Posted by Elkvis View Post
    if this code is in a production system and is used inside an inner loop of some sort, you could potentially see significant performance gains by eliminating the copy of the object.
    I bet you the compiler will optimize it. Plus since the left-hand side and right-hand side are the same, I believe it will become the same thing: initialization.
    I don't know if there are special rules for objects, but
    int n = 10
    and
    int n(10)
    are the same thing.
    Likewise is
    std::string str = "Hello World"
    and
    std::string str("Hello World")

    in any case, the way I attack a problem I'm unsure about is to write down in human language what steps *I* would take if I were going to do it by hand. then I translate that into code, and it speeds up the process a lot.
    That is an excellent advise, and what every new programmer should do. It teaches how to do proper logic in the code. Which is exactly what you, the OP, right now need.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  7. #22
    Registered User
    Join Date
    Jan 2010
    Posts
    412
    Quote Originally Posted by Elysia View Post
    I bet you the compiler will optimize it. Plus since the left-hand side and right-hand side are the same, I believe it will become the same thing: initialization.
    I don't know if there are special rules for objects, but
    int n = 10
    and
    int n(10)
    are the same thing.
    Likewise is
    std::string str = "Hello World"
    and
    std::string str("Hello World")
    Yes, and the same goes for all non-pod objects as well.
    Code:
    class MyClass
    {
      MyClass(int argument);
    };
    MyClass mc = 1;
    MyClass mc = MyClass(1);
    MyClass mc(1);
    All 3 versions gets compiled in to
    Code:
    MyClass mc = MyClass(&mc, 1)

  8. #23
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,596
    if this code is in a production system and is used inside an inner loop of some sort, you could potentially see significant performance gains by eliminating the copy of the object.
    Doubtful since they are the same thing. The code is from one of my home projects. I never post production code publicly - it is unethical and against my NDA.

    Since this is really about find() I fail to see how this adds to the discussion. And if you really must know this is from a section of code that does not need to be super fast. It is not inside of any rendering or update loop and is only performed when each sector is loaded. If I wanted it to be really really fast do you really think I would use XML?

    And so to the OP I hope some of what I posted gives you one idea of how to use find(). The documentation for it is a bit confusing so I can certainly understand not getting it the first time. I'm certainly not saying my example is the only way or the best way but it is one way. My goal was to show you one way to use it.
    Last edited by VirtualAce; 02-14-2010 at 09:25 AM.

  9. #24
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,602
    Quote Originally Posted by Elysia
    Likewise is
    std::string str = "Hello World"
    and
    std::string str("Hello World")
    Strictly speaking, they are not the same thing. The former is copy initialisation, the latter is direct initialisation, and when the constructor in question is declared explicit the former will not compile.

    Quote Originally Posted by Bubba
    Doubtful since they are the same thing.
    Semantically, I think that they are not the same thing, but any reasonable compiler will elide the copying. Still, as a matter of style I do not see a reason to use the more complicated expression here.

    The example use could be simplified to:
    Code:
    const D3DXCOLOR XMLUtils::ExtractColorFromString(const std::string &text)
    {
        float values[4] = {0.0f};
        ExtractValuesFromString<float>(text, ",", values);
        return D3DXCOLOR(values[0], values[1], values[2], values[3]);
    }
    but I do not really see the point other than to simplify your own code.

    Quote Originally Posted by Bubba
    Since this is really about find() I fail to see how this adds to the discussion.
    That is why I usually prefer to write a simplified example instead of taking something from my actual code. It is tough to find something simpler than what nick753 wants, but here's an example that prints the position of a character each time its occurrence is found in a string:
    Code:
    #include <string>
    #include <iostream>
    
    void printEach(const std::string& text, char c)
    {
        std::string::size_type i = text.find(c); // Find the first occurrence.
        while (i != std::string::npos)           // Until there are no more occurrences...
        {
            std::cout << i << std::endl;         // Print the position of the occurrence.
            i = text.find(c, i + 1);             // Find the next occurrence.
        }
    }
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  10. #25
    'Allo, 'Allo, Allo
    Join Date
    Apr 2008
    Posts
    611
    Quote Originally Posted by Bubba View Post
    Since this is really about find() I fail to see how this adds to the discussion.
    I fail to see how broken code makes for a good example.

  11. #26
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,538
    Quote Originally Posted by laserlight View Post
    Strictly speaking, they are not the same thing. The former is copy initialisation, the latter is direct initialisation, and when the constructor in question is declared explicit the former will not compile.
    Well, I wasn't trying to imply they are the same thing, just they basically translate to the same thing, and therefore, the explicit form suffers no speed penalty.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  12. #27
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,596
    I fail to see how broken code makes for a good example.
    It is not broken. The code functions just fine. As to whether or not it makes un-necessary copies is another matter but does not mean it is broken if my requirements for that section of code do not require the utmost of speed. Besides the arguments presented still are not going to cause me to change the code since it is no big deal in the grand scheme of my program. I think there are bigger fish to fry. Speed has no bearing on this section of code. Parsing the XML via tinyxml is sure to be slower than any copy operation especially if the compiler changes it as has been discussed.

    Well, I wasn't trying to imply they are the same thing, just they basically translate to the same thing, and therefore, the explicit form suffers no speed penalty.
    I cannot believe we are discussing speed in this thread when the crux of it is to show ways to use the find() function. But I digress. And I'm with just about everyone else here that speed is not going to suffer in any way. True they are not the same thing in the purest sense...but in the end the difference is not enough to cause issues.

    Good example code laserlight. The core code I presented that actually used the find function had nothing to do with the section of code that used it...yet that is what was scrutinized. Really amazing.
    Last edited by VirtualAce; 02-14-2010 at 06:14 PM.

Page 2 of 2 FirstFirst 12
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. OOP Question DB Access Wrapper Classes
    By digioz in forum C# Programming
    Replies: 2
    Last Post: 09-07-2008, 04:30 PM
  2. String issues
    By The_professor in forum C++ Programming
    Replies: 7
    Last Post: 06-12-2007, 09:11 AM
  3. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM
  4. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  5. "Operator must be a member function..." (Error)
    By Magos in forum C++ Programming
    Replies: 16
    Last Post: 10-28-2002, 01:54 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21