程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> Codeforces - cAPS lOCK 大小寫字母轉換問題

Codeforces - cAPS lOCK 大小寫字母轉換問題

編輯:C++入門知識

按如下規則轉換字母:

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 
    #include 
    #include 
    
    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<



  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved