2011-12-30 7 views
1

私は今までよりも少ない情報でこの質問をしました。いくつかのヌル終了文字を含む文字配列を別の文字列に解析する - C++

本質的には、char型のデータブロックです。このブロックには、フォーマットしてベクターに入れる必要があるファイル名が含まれています。私は当初、このcharブロックの形成に各ファイル名の間に3つのスペースがあると考えました。さて、私はそれらが '/ 0'ヌル終了文字であることを認識しています。そこで提供されたソリューションは、空の文字ではなくスペースがあると思ったときに私が与えた例では素晴らしいものでした。

構造は次のようになります。また、私は指摘する必要があります私は文字データブロックのサイズがあります。

filename1.bmp/0/0/0brick.bmp/0/0/0toothpaste.gif/0/0/0 

最善の解決策は、それをやった方法がこれだった:

// The stringstream will do the dirty work and deal with the spaces. 
    std::istringstream iss(s); 

    // Your filenames will be put into this vector. 
    std::vector<std::string> v; 

    // Copy every filename to a vector. 
    std::copy(std::istream_iterator<std::string>(iss), 
    std::istream_iterator<std::string>(), 
    std::back_inserter(v)); 

    // They are now in the vector, print them or do whatever you want with them! 
    for(int i = 0; i < v.size(); ++i) 
    std::cout << v[i] << "\n"; 

これは私の元の質問のための素晴らしい作品が、実際に彼らはヌル文字の代わりにスペースはありません。上記の例を動作させる方法はありますか?配列内のnull文字をスペースで置き換えようとしましたが、うまくいきませんでした。

文字列のベクトルにこのcharブロックをフォーマットする最も良い方法に関するアイデアはありますか?

ありがとうございました。

std::replace(std::begin(), std::end(), 0, ' '); 

を...そしてそこから行く:スペースは、適切な区切りになりたい場合

答えて

1

あなたのファイル名が埋め込まれていないわかっている場合は、「\ 0」にそれらの文字は、これは動作するはずです。

const char * buffer = "filename1.bmp/0/0/0brick.bmp/0/0/0toothpaste.gif/0/0/0"; 
int size_of_buffer = 1234; //Or whatever the real value is 

const char * end_of_buffer = buffer + size_of_buffer; 

std::vector<std::string> v; 

while(buffer!=end_of_buffer) 
{ 
    v.push_back(std::string(buffer)); 
    buffer = buffer+filename1.size()+3; 
} 

ファイル名にヌル文字が埋め込まれている場合は、少しきれいにする必要があります。 このようなものはうまくいくはずです。 (未テスト)

char * start_of_filename = buffer; 
while(start_of_filename != end_of_buffer) 
{ 

    //Create a cursor at the current spot and move cursor until we hit three nulls 
    char * scan_cursor = buffer; 
    while(scan_cursor[0]!='\0' && scan_cursor[1]!='\0' && scan_cursor[2]!='\0') 
    { 
    ++scan_cursor; 
    } 

    //From our start to the cursor is our word. 
    v.push_back(std::string(start_of_filename,scan_cursor)); 

    //Move on to the next word 
    start_of_filename = scan_cursor+3; 
} 
1

、あなただけのスペースでヌル文字を置き換えることができます。しかし、私はファイル名には通常スペースを含めることができるので、セパレータとしてヌル文字を実際に使用する必要があると思われます。この場合、std :: getline()を '\ 0'と一緒に行末に使用するか、文字列自体のfind()およびsubstr()メンバーを使用することができます。後者は、次のようになります

std::vector<std::string> v; 
std::string const null(1, '\0'); 
for (std::string::size_type pos(0); (pos = s.find_first_not_of(null, pos)) != s.npos;) 
{ 
    end = s.find(null, pos); 
    v.push_back(s.substr(0, end - pos)); 
    pos = end; 
} 
+0

名前にスペースを入れていただきありがとうございます。道路の下で大きな頭痛を避けた。 –

関連する問題