题目描述
驼峰和下划线都是对多个token组成词语的常见方法。比如对于『sensorsdata』,驼峰命名法输出『SensorsData』,而下划线命名法会输出『sensors_data』。请编写程序,输入一个驼峰,输出将其转下划线的结果。
驼峰转下划线
输入驼峰命名法的字符串,多个token会使用首字母大写来区分
输出描述
输出下划线命名法的字符串
代码示例:
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1, s2;
while (cin >> s1) {
int len = s1.size();
int flag = 1;
s2.resize(len*2);
int count = 0;
for (int i = 0; i < len; i++) {
if (s1[i] >= 'A' && s1[i] <= 'Z' && flag) {
flag = 0;
s2[i] = s1[i] - 'A' + 'a';
}
else if (s1[i] >= 'A' && s1[i] <= 'Z' && !flag) {
s2[i + count] = '_';
count++;
s2[i + count] = s1[i] - 'A' + 'a';
}
else {
s2[i + count] = s1[i];
}
}
cout << s2 << endl;
}
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
string res, s;
while (cin >> s) {
int flag = 1;
for (auto n : s) {
if (n <= 'Z' && n >= 'A' && flag) {
res.push_back(n - 'A' + 'a');
flag = 0;
}
else if (n <= 'Z' && n >= 'A' && !flag) {
res.push_back('_');
res.push_back(n - 'A' + 'a');
}
else {
res.push_back(n);
}
}
cout << res << endl;
}
}
代码生成图:
下划线转驼峰
输入下划线命名法的字符串
输出描述
输出驼峰命名法的字符串,多个token会使用首字母大写来区分
代码示例
#include <iostream>
#include <string>
using namespace std;
int main() {
string res, s;
while (cin >> s) {
int len = s.size();
res.resize(len);
res[0] = s[0] - 'a' + 'A';
int flag = 0;
int count = 0;
for (int i = 1; i < len; i++) {
if (s[i] == '_') {
flag = 1;
}
else if (flag) {
count++;
res[i - count] = s[i] - 'a' + 'A';
flag = 0;
}
else {
res[i - count] = s[i];
}
}
cout << res << endl;
res = '0'; // 清空res,防止循环输入的时候之前的res多余部分被输出
}
return 0;
}
代码生成图:
如有不同见解,欢迎留言讨论~~