QString::right does not work



  • This code:

    int split = filePath.lastIndexOf(QRegExp("/|\\\\"));
    QString test1 = filePath.left(split);
    QString test2 = filePath.right(split);
    std::cout << filePath.toStdString() << std::endl
    	<< test1.toStdString() << std::endl
    	<< test2.toStdString() << std::endl;
    

    has this output:

    D:/workspaces/Visual Studio 2015/Projects/OpenGL/Release/Msh/ic_helmet.msh
    D:/workspaces/Visual Studio 2015/Projects/OpenGL/Release/Msh
    Visual Studio 2015/Projects/OpenGL/Release/Msh/ic_helmet.msh
    

    Why is it not??

    D:/workspaces/Visual Studio 2015/Projects/OpenGL/Release/Msh/ic_helmet.msh
    D:/workspaces/Visual Studio 2015/Projects/OpenGL/Release/Msh
    /ic_helmet.msh
    

  • Moderators

    left() and right() take number of characters, not offset of the divide. So left(n) returns n leftmost characters and right(n) returns n rightmost characters, not characters after n.
    What you want here is right(filePath.size() - split).


  • Qt Champions 2016

    Hi
    Well it does work
    so most likely something with the input.

    QString x = "Pineapple";
    QString y = x.right(5); // y == "apple"

    Right() will
    "Returns a substring that contains the n rightmost characters of the string."

    But you give it the INDEX of the last seen. Not the count of chars you want from the right.

    update: Chris beat me to it :)



  • i feel stupid


  • Qt Champions 2016

    Well any productive programmer
    will make such kind of errors from time to time.

    My all time DOH is the classic

    class X {
    MyClass *mine;
    }

    and then in constructor
    MyClass *mine = new MyClass();

    and then some other place crash on
    mine->func();

    I still do that sometimes.. even after like 25 years..


  • Moderators

    @QT-static-prgm said in QString::right does not work:

    i feel stupid

    the Qt docs are written pretty good, and can save alot of time in such cases ;)


  • Qt Champions 2016

    If I may throw my 2 cents:
    Use the filesystem utilities for what you're doing and not regular expressions. Firstly, they're already tested, and secondly they're probably better as they're specialized for such tasks. For example QFileInfo is a good start.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.