0

文字の wchar_t シーケンスで出現を見つける小さな関数を開発する必要があります。この関数は文字列へのポインター wchar_t* を入力として受け取りますが、Unicode であるため、すべての文字の値は明らかに数値として表示されます。

文字列内のすべての文字を解析してユニコード番号を比較せずにこれを行うエレガントな方法はありますか? また、関数にポインターを渡そうとすると、これは最初の文字しか取得しません。なぜですか?

4

1 に答える 1

0

std::wstring正しく設定さstd::wstreamれていれば、ジョブを実行する必要があります。locale

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

static void searchAndReport(const wstring &line) {
    wstring::size_type pos = line.find(L"な"); // hiragana "na"
    if (wstring::npos == pos) {
        wcout << L"見つかりません" << endl; // not found
        return;
    }
    for (bool first = true; wstring::npos != pos; pos = line.find(L"な", pos + 1)) {
        if (first)
            first = false;
        else
            wcout << L", " ;
        wcout << L"第" << pos << L"桁" ; // the pos-th column
    }
    wcout << endl;
}

static void readLoop(wistream &is) {
    wstring line;

    for (int cnt = 0; getline(is, line); ++cnt) {
        wcout << L"第" << cnt << L"行目: " ; // the cnt-th line:
        searchAndReport(line);
    }
}

int main(int argc, char *argv[]) {
//  locale::global(std::locale("ja_JP.UTF-8"));
    locale::global(std::locale(""));

    if (1 < argc) {
        wcout << L"入力ファイル: [" << argv[1] << "]" << endl; // input file
        wifstream ifs( argv[1] );
        readLoop(ifs);
    } else {
        wcout << L"標準入力を使用します" << endl; // using the standard input
        readLoop(wcin);
    }
}

転写:

$ cat scenery-by-bocho-yamamura.txt
いちめんのなのはな
いちめんのなのはな
いちめんのなのはな
いちめんのなのはな
いちめんのなのはな
いちめんのなのはな
いちめんのなのはな
かすかなるむぎぶえ
いちめんのなのはな
$ ./wchar_find scenery-by-bocho-yamamura.txt
入力ファイル: [scenery-by-bocho-yamamura.txt]
第0行目: 第5桁, 第8桁
第1行目: 第5桁, 第8桁
第2行目: 第5桁, 第8桁
第3行目: 第5桁, 第8桁
第4行目: 第5桁, 第8桁
第5行目: 第5桁, 第8桁
第6行目: 第5桁, 第8桁
第7行目: 第3桁
第8行目: 第5桁, 第8桁

すべてのファイルは UTF-8 です。

coutとを混ぜないように注意してくださいwcout

環境:

$ lsb_release -a
LSB Version:    core-2.0-amd64: [...snip...]
Distributor ID: Ubuntu
Description:    Ubuntu 12.04.5 LTS
Release:        12.04
Codename:       precise
$ env | grep -i ja
LANGUAGE=ja:en
GDM_LANG=ja
LANG=ja_JP.UTF-8
$ g++ --version
g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
Copyright (C) 2011 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
于 2014-09-03T01:24:04.863 に答える