どう抜く?のお題、文字列の反転。
うーん。まだ洗練しきれてない感じがする。
#include <iostream> #include <string> bool isLeadChar(std::string::value_type c) { unsigned char uc = c; return ((0x80u <= uc) && (uc <= 0x9fu)) || ((0xa1u <= uc) && (uc <= 0xfeu)); } class CharReader { public: explicit CharReader(const std::string& src) : src_(src), pos_(0) {} std::string next() { std::string result; if((pos_ < src_.length()) && isLeadChar(src_[pos_])) { result = src_.substr(pos_, 2); pos_ += 2; } else { result = src_.substr(pos_, 1); ++pos_; } return result; } bool isEmpty() const { return src_.length() <= pos_; } private: const std::string src_; std::string::size_type pos_; }; std::string reverse_string(const std::string& src) { CharReader reader(src); std::string result; while( ! reader.isEmpty()) { result = reader.next() + result; } return result; } int main(int, char* []) { std::cout << reverse_string("Hello") << std::endl; std::cout << reverse_string("こんにちは") << std::endl; std::cout << reverse_string("濁点(だくてん)") << std::endl; return 0; }