What is common way to split string into list with CMAKE?

Cmake

Cmake Problem Overview


Imagine I have the following string :

set(SEXY_STRING "I love CMake")

then I want to obtain SEXY_LIST from SEXY_STRING so I can do

list(LENGTH SEXY_LIST len)

and len is equal 3.

I've found several macros on web, but I really want to know how to do it in "natural" way. This operation seems to be very basic and widely used.

Cmake Solutions


Solution 1 - Cmake

Replace your separator by a ;. I don't see any other way to do it.

cmake_minimum_required(VERSION 2.8)

set(SEXY_STRING "I love CMake")
string(REPLACE " " ";" SEXY_LIST ${SEXY_STRING})

message(STATUS "string = ${SEXY_STRING}")
# string = I love CMake

message(STATUS "list = ${SEXY_LIST}")
# list = I;love;CMake

list(LENGTH SEXY_LIST len)
message(STATUS "len = ${len}")
# len = 3

Solution 2 - Cmake

You can use the separate_arguments command.

cmake_minimum_required(VERSION 2.6)

set(SEXY_STRING "I love CMake")

message(STATUS "string = ${SEXY_STRING}")
# string = I love CMake

set( SEXY_LIST ${SEXY_STRING} )
separate_arguments(SEXY_LIST)

message(STATUS "list = ${SEXY_LIST}")
# list = I;love;CMake

list(LENGTH SEXY_LIST len)
message(STATUS "len = ${len}")
# len = 3

Solution 3 - Cmake

string(REGEX MATCHALL "[a-zA-Z]+\ |[a-zA-Z]+$" SEXY_LIST "${SEXY_STRING}")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexander K.View Question on Stackoverflow
Solution 1 - CmaketiburView Answer on Stackoverflow
Solution 2 - CmaketillaertView Answer on Stackoverflow
Solution 3 - CmakeAlexander K.View Answer on Stackoverflow