challenge 文字列の反転

与えられた文字列sを前後逆転したものを返す関数reverse_stringを作成してください。 ただし、sはShift-JISでエンコードされている文字列だと仮定して構いません。

サンプル入出力

>>> print reverse_string("Hello")
olleH
>>> print reverse_string("こんにちは")
はちにんこ
>>> print reverse_string("濁点(だくてん)")
)んてくだ(点濁

Posted feedbacks - C++

WindowsAPIのCharNextExを使用。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <windows.h>
#include <iostream>
#include <string>

std::string reverse_string(const char* s, WORD codepage = 932)
{
    std::string ret;

    while (*s)
    {
        const char* p = ::CharNextExA(codepage, s, 0);

        ret.insert(0, s, p - s);

        s = p;
    }

    return ret;
}

int main()
{
    std::cout << reverse_string("Hello") << std::endl;
    std::cout << reverse_string("こんにちは") << std::endl;
    std::cout << reverse_string("濁点(だくてん)") << std::endl;
}


	
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#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;
}


	
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool is_sjis(unsigned char c) {
    return ((0x81 <= c) && (c <= 0x9F)) || ((0xE0 <= c) && (c <= 0xEF));
}
string reverse_string(const string &_s) {
	string s(_s.rbegin(), _s.rend());
	for (string::reverse_iterator ite = s.rbegin(); ite != s.rend(); ++ite) {
		if (is_sjis(*ite)) {
			iter_swap(ite, ite + 1);
			++ite;
		}
	}
	return s;
}
int main() {
	cout << reverse_string("Hello") << endl;
	cout << reverse_string("こんにちは") << endl;
	cout << reverse_string("濁点(だくてん)") << endl;
	return 0;
}

Index

Feed

Other

Link

Pathtraq

loading...