2

Is there a function in Сmake to reverse a string? I have a variable containing the string "abcd" and I need to get the string "dcba" from it. If there is no such function, what should I do?

I read the documentation but didn't find the required function there.

Zhenya4880
  • 31
  • 1
  • 5
  • 1) you could use `execute_process` to run a command/program that reverses strings. But that might not score too well in the cross-platform category. 2) note: a related generator expression proposal is here: https://gitlab.kitware.com/cmake/cmake/-/issues/20614 – starball Jul 12 '23 at 19:18

2 Answers2

0

There is no such command. I would try splitting your string into a list, which requires adding a ; character to split on, because:

A list in cmake is a ; separated group of strings

Then reversing the list, then joining it back together. Something like:

string(REPLACE "" ";" output ${delimited})
list(REVERSE delimited reversed_list)
list(JOIN reversed_list "" reversed_string)
message(STATUS "reversed: ${reversed_string}")

This is entirely untested. See also this answer for more string/list manipulation examples.

Andy Ray
  • 30,372
  • 14
  • 101
  • 138
0

There is no such function, but creating one is not so hard. Here is the one possible implementation:

#the function to reverse the string
function (string_reverse INPUT_STRING OUTPUT_VAR)

    string(LENGTH ${INPUT_STRING} len)
    set(out "")
    foreach(indx RANGE ${len})
        string(SUBSTRING ${INPUT_STRING} ${indx} 1 char)
        string(PREPEND out ${char})
    endforeach()

    set(${OUTPUT_VAR} ${out} PARENT_SCOPE)
endfunction()

The usage of the function reverse_string would be as follows. Please note that the code expects the function definition to be available now.

# prepare the string to be reversed
set(ORIGINAL_STRING "123 45 67 890 a b c d e fgh I J K LMNO  PQ")

# call the function to reverse the string
string_reverse(${ORIGINAL_STRING} REVERSED_STRING)

# debugging output
message ("ORIGINAL_STRING: ${ORIGINAL_STRING}")
message ("REVERSED_STRING: ${REVERSED_STRING}")

Note that the variable REVERSED_STRING will be created and initialized within the function, so it is unnecessary to do it explicitly.

After running this code, the output would be as follows:

ORIGINAL_STRING: 123 45 67 890 a b c d e fgh I J K LMNO  PQ
REVERSED_STRING: QP  ONML K J I hgf e d c b a 098 76 54 321

BTW, what are you trying to achieve? i.e., why do you need string reversal within cmake?

gordan.sikic
  • 1,174
  • 8
  • 8