[每日一题]88:驼峰与下划线互相转化(C/C++)

题目描述

驼峰和下划线都是对多个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;
}

代码生成图:

在这里插入图片描述


如有不同见解,欢迎留言讨论~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值