[CMake] Return value of cmake string find

David Cole dlrdave at aol.com
Mon Jun 9 06:23:12 EDT 2014


> What is returned if string(FIND) matches a substring, and what is
> returned if it doesn't match anything?

The documentation says:
http://cmake.org/cmake/help/v2.8.12/cmake.html#command:string
http://www.cmake.org/cmake/help/v3.0/command/string.html
string(FIND <string> <substring> <output variable> [REVERSE])
"FIND will return the position where the given substring was found in
the supplied string."

Wow, that's on the light side.

When the documentation is insufficient, experimentation is your
friend... (or source code analysis)
This script:
    string(FIND "this is a haystack, purely hay" "needle" pos1)
    message("pos1='${pos1}'")

    string(FIND "needle resting right on a haystack" "needle" pos2)
    message("pos2='${pos2}'")

    string(FIND "a haystack on top of a needle" "needle" pos3)
    message("pos3='${pos3}'")

     string(FIND "a haystack with a needle buried in the middle of it"
"needle" pos4)
    message("pos4='${pos4}'")

     string(FIND "needle hay hay needle hay hay needle hay hay needle"
"needle" pos5)
    message("pos5='${pos5}'")

    string(FIND "this is a haystack, purely hay" "needle" pos6 REVERSE)
    message("pos6='${pos6}'")

     string(FIND "needle resting right on a haystack" "needle" pos7
REVERSE)
    message("pos7='${pos7}'")

    string(FIND "a haystack on top of a needle" "needle" pos8 REVERSE)
    message("pos8='${pos8}'")

     string(FIND "a haystack with a needle buried in the middle of it"
"needle" pos9 REVERSE)
    message("pos9='${pos9}'")

     string(FIND "needle hay hay needle hay hay needle hay hay needle"
"needle" pos10 REVERSE)
    message("pos10='${pos10}'")

Produces this output:
    pos1='-1'
    pos2='0'
    pos3='23'
    pos4='18'
    pos5='0'
    pos6='-1'
    pos7='0'
    pos8='23'
    pos9='18'
    pos10='45'

The C++ source code implementation uses std::string::find, or if the
REVERSE option is used, std::string::rfind. The returned value is
exactly what find or rfind returns if the substring is found, or it is
exactly "-1" if it is not found. So: a zero-based offset from the
beginning of the string, where a value of zero means the
substring occurs starting at the very first character of the string.


HTH,
David C.






More information about the CMake mailing list