ページ 11

STLを用いた文字の検索について

Posted: 2012年8月22日(水) 00:43
by taketoshi
szCommetBuffという名前のバッファにためた文字列から
半角のアットマークとアポストロフィを検索したくて
STLを用いて以下のようなコードを書きました

コード:

int szBanCheck(char *szCommetBuff){
	string szStr;

	//登録禁止文字列
	char *szBan[] = {"@","'"};

	int nBan,j;
	//禁止文字を含んでいないかの確認
	szStr = szCommetBuff;
	for(j = 0;j < sizeof(szBan) / sizeof(szBan[0]);++j){
		nBan = szStr.find_first_of(szBan[j],0);
		if(string::npos != nBan){
			return -1;
		}
	}
	return 0;
}
上記コードを実行すると「機械」の「機」文字まではじかれてしまうのですが・・・
何故でしょうか。文字コードとかの問題ですか・・?

何方かヒントを下さい。ご教授お願いいたします。

Re: STLを用いた文字の検索について

Posted: 2012年8月22日(水) 07:49
by みけCAT
おそらく文字コードの問題ですね。
このへんを参考にどうぞ。
http://www.tohoho-web.com/wwwkanji.htm

Re: STLを用いた文字の検索について

Posted: 2012年8月22日(水) 11:20
by かずま
文字コードが Shift-JIS の場合、「機」は 8b 40 です。「@」は 40 です。
wchar_t や wstring が使える環境では、次のコードはどうでしょうか?

コード:

#include <iostream>
#include <string>
#include <clocale>

using namespace std;

int szBanCheck(const char *str)
{
    string s = str;
    size_t size = s.size() + 1;
    wchar_t *wcs = new wchar_t[size];
    mbstowcs(wcs, str, size);
    wstring ws = wcs;
    delete[] wcs;
    size_t nBan = ws.find_first_of(L"@'");
    return (nBan == wstring::npos) ? 0 : -1;
}

int main()
{
    string s;
    setlocale(LC_CTYPE, "");
    while (getline(cin, s))
        cout << szBanCheck(s.c_str()) << endl;
}

Re: STLを用いた文字の検索について

Posted: 2012年8月23日(木) 23:47
by かずま
Shift JIS 限定なら、こんな風にも書けます。

コード:

#include <iostream>
#include <string>
 
using namespace std;
 
bool isleading(unsigned char c) { return (c ^ 0x20) - 0xa1u < 60; }

int szBanCheck(const char *s1, const char *s2)
{
    for (; *s1; s1++)
        if (isleading(*s1)) {
            if (*++s1 == 0) return 0;
        } else
            for (const char *p = s2; *p; p++)
                if (*s1 == *p) return -1;
    return 0;
}
 
int main()
{
    string s;
    while (getline(cin, s))
        cout << szBanCheck(s.c_str(), "@'") << endl;
}

Re: STLを用いた文字の検索について

Posted: 2012年8月31日(金) 16:47
by taketoshi
皆様お返事ありがとうございます。
仕事でなかなかプログラムを組む時間が取れなかったので遅くなって申し訳ありません。

みけCATさんが提示してくれたサイトを読んで暫く勉強してきて
お二人の提示してくれたコードを基に改変したところ、使えるようになりました。
ありがとうございます