文字列変換したいとき、明示的に変数で扱う必要はかならずしもない
C++の基本的な文法に慣れたいので、今夜もTopCoderの過去問を解きます。
SRM210 div2 (250)
問題
スペース混じりの英文字列を与え、本のタイトルのように単語の先頭文字だけを大文字に変換した文字列を返す。
その際、スペースの個数は維持する。たとえば、こんな感じ。
2)
" lord of the rings the fellowship of the ring "
Returns: " Lord Of The Rings The Fellowship Of The Ring "
自分の解答
#include <string> #include <iostream> class TitleString { public: std::string toFirstUpperCase(std::string title); }; std::string TitleString::toFirstUpperCase(std::string title) { if(title.size() == 0){ return ""; } std::string result; int count = 0; for(int i = 0; i < title.size(); ++i){ if(title[i] == ' '){ result += ' '; count = 0; } else { if(count == 0) { result += toupper(title[i]); } else { result += title[i]; } ++count; } } return result; }
人様のコードを読んだ感想
toupperやインデックスアクセスの戻り値を使って、文字列を作りましたが、その必要はないんですね。必要な箇所を大文字にするだけでよかったようです。
条件も、「1文字目、あるいは、前の文字が空白の場合」でthat's allでした。
他にも、範囲外エラーを避けるために、文字列に空白を1つ足してからループを回して、最後に除去する処理や、大文字にするために &= ~32 する処理など、味わい深い解答が見られました。