> 技术文档 > CMake字符串string命令常见用法示例

CMake字符串string命令常见用法示例


CMake string 命令常见用法示例

CMake 的 string 命令提供了丰富的字符串操作功能,下面是一些常见用法的示例:

1. 字符串查找和替换

# 查找子字符串string(FIND \"Hello World\" \"World\" position)message(\"Found at position: ${position}\") # 输出 6# 替换字符串string(REPLACE \"World\" \"CMake\" result \"Hello World\")message(\"${result}\") # 输出 \"Hello CMake\"

2. 字符串大小写转换

# 转换为大写string(TOUPPER \"hello\" upper_result)message(\"${upper_result}\") # 输出 \"HELLO\"# 转换为小写string(TOLOWER \"HELLO\" lower_result)message(\"${lower_result}\") # 输出 \"hello\"

3. 字符串长度和子字符串

# 获取字符串长度string(LENGTH \"Hello\" len)message(\"Length: ${len}\") # 输出 5# 获取子字符串string(SUBSTRING \"Hello World\" 6 5 substr)message(\"${substr}\") # 输出 \"World\"

4. 字符串拼接和连接

# 拼接多个字符串string(CONCAT concatenated \"Hello\" \" \" \"World\")message(\"${concatenated}\") # 输出 \"Hello World\"# 使用 JOIN 连接列表set(words Hello World From CMake)string(JOIN \" \" joined_words ${words})message(\"${joined_words}\") # 输出 \"Hello World From CMake\"

5. 字符串比较

# 比较字符串string(COMPARE EQUAL \"hello\" \"HELLO\" result)message(\"Equal? ${result}\") # 输出 0 (false)string(COMPARE EQUAL \"hello\" \"hello\" result)message(\"Equal? ${result}\") # 输出 1 (true)

6. 字符串去除空格

# 去除开头和结尾的空格string(STRIP \" Hello World \" stripped)message(\"|${stripped}|\") # 输出 \"|Hello World|\"

7. 正则表达式操作

# 正则匹配string(REGEX MATCH \"[0-9]+\" matched \"Version 123\")message(\"Matched: ${matched}\") # 输出 \"123\"# 正则替换string(REGEX REPLACE \"[0-9]+\" \"456\" replaced \"Version 123\")message(\"${replaced}\") # 输出 \"Version 456\"

8. 字符串编码转换

# 将字符串转换为十六进制表示string(ASCII 65 66 67 hex_str)message(\"${hex_str}\") # 输出 \"ABC\"# 计算字符串的哈希值string(MD5 hash_value \"Hello World\")message(\"MD5: ${hash_value}\")

这些示例展示了 CMake string 命令的一些常见用法,实际使用时可以根据需要组合这些操作来处理复杂的字符串任务。