Codeforces - cAPS lOCK 大小写字母转换问题

本文介绍了一种通过自动转换字母大小写来解决Capslock按键意外开启的问题,包括程序实现和自动化的流程。文章详细阐述了解决方案的逻辑,通过状态机实现了对输入字符串中字母大小写的智能判断与转换,确保了文字输入的准确性与一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

按如下规则转换字母:

Let's consider that a word has been typed with the Caps lock key accidentally switched on, if:

  • either it only contains uppercase letters;
  • or all letters except for the first one are uppercase.

In this case we should automatically change the case of all letters. For example, the case of the letters that form words "hELLO", "HTTP", "z" should be changed.

单个大写字母是否需要转换?需要。

cBCD -> Cbcd

Good -> Good

H -> h

h -> H

看似乎简单,但是解决这个问题可以,要优雅地写出程序,那么就是不容易的了。

下面看我的程序,使用automata的知识,写个小小的automata系统,优雅地解决这个问题:

#include <iostream>
#include <vector>
#include <string>

using namespace std;

enum CASE
{
	ALL_UPPERS,
	ONLY_FIRST_LOWER,
	CORRECT,
	ILEGAL
};

const static int trans[6][2] = {
	{1,	2},					//0 Init and Invalid
	{3,	5},					//1 first upper
	{4,	5},					//2 first lower
	{3,	5},					//3 all upper
	{4,	5},					//4 first low other upper
	{5,	5}	};				//5 correct words

CASE checkLetters(string &s)
{
	int state = 0;
	for (int i = 0; i < s.size(); i++)
	{
		int input = -1;
		if ('A' <= s[i] && s[i] <= 'Z') input = 0;
		if ('a' <= s[i] && s[i] <= 'z') input = 1;
		if (-1 == input) return ILEGAL;
		state = trans[state][input];
	}
	if (1 == state || 3 == state) return ALL_UPPERS;
	else if (2 == state || 4 == state) return ONLY_FIRST_LOWER;
	return CORRECT;
}

void transAllLowers(string &s)
{
	for (int i = 0; i < s.size(); i++)
	{
		s[i] = s[i] - 'A' + 'a';
	}
}

void transFirstUpper(string &s)
{
	s[0] = s[0] - 'a' + 'A';
	for (int i = 1; i < s.size(); i++)
	{
		s[i] = s[i] - 'A' + 'a';
	}
}

void cAPSLOOCK()
{
	string s;
	cin>>s;	
	CASE C = checkLetters(s);
	if (ALL_UPPERS == C) transAllLowers(s);
	else if (ONLY_FIRST_LOWER == C) transFirstUpper(s);
	else if (ILEGAL == C) cout<<"ILEGAL", exit(0);
	cout<<s;
}

int main()
{
	cAPSLOOCK();
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值