• 驼峰风格、下划线风格互转


     1 /**
     2  * 将驼峰式命名的字符串转换为下划线大写方式。如果转换前的驼峰式命名的字符串为空,则返回空字符串。</br>
     3  * 例如:HelloWorld->HELLO_WORLD
     4  * @param name 转换前的驼峰式命名的字符串
     5  * @return 转换后下划线大写方式命名的字符串
     6  */
     7 public static String underscoreName(String name) {
     8     StringBuilder result = new StringBuilder();
     9     if (name != null && name.length() > 0) {
    10         // 将第一个字符处理成大写
    11         result.append(name.substring(0, 1).toUpperCase());
    12         // 循环处理其余字符
    13         for (int i = 1; i < name.length(); i++) {
    14             String s = name.substring(i, i + 1);
    15             // 在大写字母前添加下划线
    16             if (s.equals(s.toUpperCase()) && !Character.isDigit(s.charAt(0))) {
    17                 result.append("_");
    18             }
    19             // 其他字符直接转成大写
    20             result.append(s.toUpperCase());
    21         }
    22     }
    23     return result.toString();
    24 }
    25  
    26 /**
    27  * 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。</br>
    28  * 例如:HELLO_WORLD->HelloWorld
    29  * @param name 转换前的下划线大写方式命名的字符串
    30  * @return 转换后的驼峰式命名的字符串
    31  */
    32 public static String camelName(String name) {
    33     StringBuilder result = new StringBuilder();
    34     // 快速检查
    35     if (name == null || name.isEmpty()) {
    36         // 没必要转换
    37         return "";
    38     } else if (!name.contains("_")) {
    39         // 不含下划线,仅将首字母小写
    40         return name.substring(0, 1).toLowerCase() + name.substring(1);
    41     }
    42     // 用下划线将原始字符串分割
    43     String camels[] = name.split("_");
    44     for (String camel :  camels) {
    45         // 跳过原始字符串中开头、结尾的下换线或双重下划线
    46         if (camel.isEmpty()) {
    47             continue;
    48         }
    49         // 处理真正的驼峰片段
    50         if (result.length() == 0) {
    51             // 第一个驼峰片段,全部字母都小写
    52             result.append(camel.toLowerCase());
    53         } else {
    54             // 其他的驼峰片段,首字母大写
    55             result.append(camel.substring(0, 1).toUpperCase());
    56             result.append(camel.substring(1).toLowerCase());
    57         }
    58     }
    59     return result.toString();
    60 }
  • 相关阅读:
    函数参数传递
    C# 串口发送 陷阱,必须知道的坑
    Altera Quartus 13.1 仿真工具路径错误问题解决 Can't launch the ModelSim-Altera software
    Altium Designer 快速修改板子形状为Keep-out layer大小
    Altium Designer 敷铜间距设置,真实有效
    VS2012,VS2013启用SQLite的Data Provider界面显示
    Sqlite 设置外键级联更新
    Sqlite 设置默认时间为本地时间
    FPGA学习笔记之Altera FPGA使用JIC文件配置固化教程(转)
    FPGA学习记录
  • 原文地址:https://www.cnblogs.com/chenhao1990/p/4628977.html
Copyright © 2020-2023  润新知