Results 1 to 2 of 2

Thread: better way to get index of substring?

  1. #1
    Join Date
    Jul 2012
    Posts
    218
    Thanks
    17
    Thanked 14 Times in 13 Posts
    Qt products
    Qt4
    Platforms
    Windows

    Default better way to get index of substring?

    Hey,

    I find myself often needing to find the index of a substring *after* the substring.
    So I end up with this pattern a lot:


    Qt Code:
    1. str.left(std.indexOf("something") + strlen("something"))
    To copy to clipboard, switch view to plain text mode 

    or

    Qt Code:
    1. str.left(std.indexOf("something") + 9)
    To copy to clipboard, switch view to plain text mode 


    In one case I have to count chars by hand, in the other I have to duplicate the string.


    Is there a better way to do it?

  2. #2
    Join Date
    Jan 2006
    Location
    Graz, Austria
    Posts
    8,183
    Thanks
    36
    Thanked 1,489 Times in 1,441 Posts
    Qt products
    Qt3 Qt4 Qt5
    Platforms
    Unix/X11 Windows

    Default Re: better way to get index of substring?

    Well, duplication is only necessary because you don't have the substring in a variable.

    Qt Code:
    1. const QString substring("something");
    2. str.left(str.indexOf(substring) + substring.length());
    To copy to clipboard, switch view to plain text mode 

    Alternatively, a regular expression match could be used to extract the result. Something like
    Qt Code:
    1. QRegularExpression pattern("^(.*)something"); // any characters from the beginning of the string until "something"
    2.  
    3. QRegularExpressionMatch match = pattern.match(str);
    4. if (match.hasMatch()) {
    5. // result in match.captured(1);
    6. }
    To copy to clipboard, switch view to plain text mode 
    Probably only worth though it if the you look for the same pattern in a lot of string.

    Cheers,
    _

Similar Threads

  1. Replies: 1
    Last Post: 1st December 2011, 13:11
  2. getting the substring with delimiter
    By meena in forum Qt Programming
    Replies: 3
    Last Post: 6th July 2010, 13:38
  3. Highlighting substring problem
    By chandan in forum Newbie
    Replies: 1
    Last Post: 18th April 2010, 18:01
  4. How to check if a string starts with a substring?
    By lni in forum Qt Programming
    Replies: 3
    Last Post: 18th April 2007, 01:36
  5. Replies: 2
    Last Post: 10th February 2006, 13:57

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.