字符串驼峰命名转换———以Java和JavaScript写法为例

流程思路

字符串驼峰命名转换

Java写法

import java.util.Arrays;

//转换驼峰字符串例:hello-world   =>   helloWorld
public class Hump {
    public static void main(String[] args) {
        System.out.println(toHupm("hello-world"));
    }

    private static String toHupm(String foo) {

        String[] arr;
        String newData = null;
        //以'-'字符为切割点进行切割
        arr = foo.split("-");
        System.out.println(Arrays.toString(arr));
        for (int i = 0; i < arr.length; i++) {
        //首个切割片段首字母小写 + 首个切割片段剩余其他字符
            if (i == 0) {
                arr[i] = String.valueOf(arr[i].charAt(0)).toLowerCase() + arr[i].substring(1);
                newData = arr[i];
            } 
            //非首个切割片段首字母大写 + 切割片段剩余其他字符
            else {
                arr[i] = String.valueOf(arr[i].charAt(0)).toUpperCase() + arr[i].substring(1);
                newData = newData + arr[i];
            }
        }
        return newData;
    }
}


Java写法验证结果

Java写法验证结果

JavaScript写法

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>hump</title>
</head>

<body>
    <script type="text/javascript">
        //转换驼峰字符串例:hello-world   =>   helloWorld
        function toHump(foo) {
        //以'-'字符为切割点进行切割
            var arr = foo.split('-');

            for (var i = 0; i < arr.length; i++) {
            //首个切割片段首字母小写 + 首个切割片段剩余其他字符
                if (i == 0) {
                    arr[i] = arr[i].charAt(0).toLowerCase() + arr[i].substr(1, arr[i].length - 1);               
                }
                else {
            //非首个切割片段首字母大写 + 切割片段剩余其他字符
                    arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].substr(1, arr[i].length - 1);
                }
            }

            return arr.join('');
        }
        console.log(toHump('hello-world'));

    </script>

</body>

</html>

JavaScript验证结果

JavaScript写法验证

小结

这里主要是针对简单固定形式的字符串进行转换,遇到一些复杂的还需重新确定思路,见招拆招,随机应变了。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值