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

被折叠的 条评论
为什么被折叠?



