Convert string to camel case-将字符串转换为驼峰大小写

我的个人博客

更多内容,请跳转我的个人博客

题目

Convert string to camel case(将字符串转换为驼峰大小写)

描述

Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case).

完成该方法/函数,使其将破折号/下划线分隔的单词转换为骆驼大写字母。只有在原词大写的情况下,输出内的第一个词才应大写(称为上驼峰大小写,也常被称为帕斯卡大小写)。

例子

“the-stealth-warrior” gets converted to “theStealthWarrior”
“The_Stealth_Warrior” gets converted to “TheStealthWarrior”

思路

本题的关键就是对于_和-的处理,但是因为本题的关键点也就是这么两个,所以处理起来并不复杂,只要设置一个标志(本题我们使用了保存前一个字母的方式)

  1. 当pre是上面的-和_的时候,就将当前个字母变为大写字母即可,后面不变。
  2. 当当前的字符是-和_的时候,跳过

全部代码

def to_camel_case(text):
    #your code here
    # 创建一个列表,用来保存结果
    result = []
    # 创建一个值用来保存上一个字符
    pre = ""
    # 如果text是空的,那么就返回空
    if text == "":
        return ""
    for i in range(len(text)):
        # 如果pre是“-”or"_"就当前的字母装换为大写,其他的自动添加
        if text[i] != "_" and text[i] != "-":
            if pre == "_" or pre == "-":
                result.append(text[i].upper())
            else:
                result.append(text[i])
        pre = text[i]
    return ''.join(result)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值