字符串的下划线命名和驼峰命名转换

9 篇文章 0 订阅

字符串的下划线命名和驼峰命名转换

java

/** 
 * 将驼峰式命名的字符串转换为下划线大写方式。如果转换前的驼峰式命名的字符串为空,则返回空字符串。</br> 
 * 例如:HelloWorld->HELLO_WORLD 
 * @param name 转换前的驼峰式命名的字符串 
 * @return 转换后下划线大写方式命名的字符串 
 */  
publicstatic String underscoreName(String name) {  
    StringBuilder result = newStringBuilder();  
    if(name != null&& name.length() > 0) {  
        // 将第一个字符处理成大写  
        result.append(name.substring(0,1).toUpperCase());  
        // 循环处理其余字符  
        for(inti = 1; i < name.length(); i++) {  
            String s = name.substring(i, i + 1);  
            // 在大写字母前添加下划线  
            if(s.equals(s.toUpperCase()) && !Character.isDigit(s.charAt(0))) {  
                result.append("_");  
            }  
            // 其他字符直接转成大写  
            result.append(s.toUpperCase());  
        }  
    }  
    returnresult.toString();  
}  

C++

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <cctype>
#include <fstream>
#define INF 0x3f3f3f3f
#define EPS 1e-24
using namespace std;

typedef long long ll;
const ll Mod = 1e9 + 7;

int main(){
    std::ios::sync_with_stdio(false);
    std::cin.tie(0);

    int n;
    while(cin>>n){
        for(int i=0;i<n;i++){
            string s;
            cin>>s;
            if(s.find('_')!=string::npos){
                int pos = s.find('_');
                s.erase(pos,1);
                s[pos] = toupper(s[pos]);
            }
            else{
                int pos;
                for(int j=0;j<s.size();j++){
                    if(s[j] > 'A' && s[j] < 'Z'){
                        pos = j;
                        break;
                    }
                }
                s.insert(pos,"_");
                s[pos+1] = tolower(s[pos+1]);
            }
            cout<< s <<endl;
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值