hihoCoder 1501-风格不统一如何写程序

hihoCoder 1501-风格不统一如何写程序

#1501 : 风格不统一如何写程序

时间限制:10000ms
单点时限:1000ms
内存限制:256MB

描述

小Hi写程序时习惯用蛇形命名法(snake case)为变量起名字,即用下划线将单词连接起来,例如:file_name、 line_number。 小Ho写程序时习惯用驼峰命名法(camel case)为变量起名字,即第一个单词首字母小写,后面单词首字母大写,例如:fileName、lineNumber。 为了风格统一,他们决定邀请公正的第三方来编写一个转换程序,可以把一种命名法的变量名转换为另一种命名法的变量名。 你能帮助他们解决这一难题吗?

输入

第一行包含一个整数N,表示测试数据的组数。(1 <= N <= 10) 以下N行每行包含一个以某种命名法命名的变量名,长度不超过100。 输入保证组成变量名的单词只包含小写字母。

输出

对于每组数据,输出使用另一种命名法时对应的变量名。
样例输入
2
file_name
lineNumber
样例输出
fileName
line_number

本题要求把蛇形命名法和驼峰命名法相互转换。简单题,首先判断字符串中是否有下划线来区分原命名法,然后遍历字符串,找下划线或者大写字母,然后直接转换即可。 代码如下,注意在getline之前把换行符读了。 [cpp] #include<iostream> #include<cstdio> #include<vector> #include<algorithm> #include<unordered_map> #include<string> using namespace std; int main() { //freopen("input.txt", "r", stdin); int n; char c; scanf("%d", &n); scanf("%c", &c); // 读取换行符\n string line; while (n–) { getline(cin, line); if (line.find(‘_’) != string::npos) { string ans = ""; int len = line.size(), i = 0, j = 0; for (j = 0; j < len; ++j) { if (line[j] == ‘_’&&j + 1 < len) { line[j + 1] = toupper(line[j + 1]); ans += line.substr(i, j – i); i = j + 1; } } ans += line.substr(i, j – i); cout << ans << endl; } else { string ans = ""; int len = line.size(), i = 0, j = 0; for (j = 0; j < len; ++j) { if (isupper(line[j])) { line[j] = tolower(line[j]); if(ans=="") ans += line.substr(i, j – i); else ans += "_" + line.substr(i, j – i); i = j; } } ans += "_" + line.substr(i, j – i); cout << ans << endl; } } return 0; } [/cpp] 本代码提交AC,用时0MS。]]>

Leave a Reply

Your email address will not be published. Required fields are marked *