Go语言中如何将含空格的字符串转换为camelCase格式?
空格字符串转camelCase格式的最简实现
核心转换逻辑
- 先去除输入字符串的首尾空格,按任意数量的空白字符分割为独立单词列表
- 首个单词统一转为全小写
- 从第二个单词开始,每个单词首字母大写,剩余字符可按需求选择保持原有格式或统一小写
- 把所有处理后的单词片段直接拼接得到最终camelCase字符串
示例验证:
输入:"This is a string with spaces"
分割得到单词列表:["This", "is", "a", "string", "with", "spaces"]
首个单词转小写得到"this",后续单词分别处理为首字母大写的Is、A、String、With、Spaces
拼接后输出:"thisIsAStringWithSpaces"
不同语言的最简代码实现
JavaScript
单行函数实现,自动兼容连续空格、首尾空格场景:
const toCamelCase = str => str.trim().split(/\s+/).reduce((result, word, index) => index === 0 ? word.toLowerCase() : result + word[0].toUpperCase() + word.slice(1), '')
调用示例:toCamelCase("This is a string with spaces")
返回结果:thisIsAStringWithSpaces
Python
利用内置字符串方法实现,简洁易读:
def to_camel_case(input_str: str) -> str: words = input_str.strip().split() # 需保留单词非首字母原有大小写时,将word.capitalize()替换为word[0].upper() + word[1:]即可 return words[0].lower() + ''.join(word.capitalize() for word in words[1:])
调用示例:to_camel_case("This is a string with spaces")
返回结果:thisIsAStringWithSpaces
边界场景适配
上述实现已自动覆盖常见异常场景:
- 输入字符串首尾带多余空格,比如
" Hello world "会转换为helloWorld - 单词之间存在多个连续空格,比如
"Hello world test"会转换为helloWorldTest - 单个单词输入,比如
"Hello"会转换为hello
内容的提问来源于stack exchange,提问作者Sam Berry
相关产品推荐
相关产品推荐

