幼稚園時代「何組」でしたか?

先ほどジャンル違いで質問してしまったので、再度C/C++の方へ質問いたします。

string str = "AABBCCDD";

これを以下のように分割する方法が知りたいです。
result[0] = "AA";
result[1] = "BB";
result[2] = "CC";
result[3] = "DD";

分割する固定長2と、結果を保存するstring型のresultを与えれば
以下のようになる関数を作りたいのですが、
C++の標準機能でスマートにできる方法がベストです。


Perlでいうunpack見たいなものです。
use strict;

my $str = "AABBCCDD";
my @result = unpack '(a2)*', $str; // こんなことをC++でしたい
foreach my $val (@result) {
print $val, "\n";
}

よろしくお願いします。

A 回答 (1件)

たとえばこんなの。



#include <iostream>
#include <string>
#include <vector>

using namespace std;

string cut(string& str, int n) {
string result = str.substr(0,n);
str.erase(0,n);
return result;
}

int main() {
vector<string> output;

string input = "AABBCCDD";
while ( !input.empty() ) {
output.push_back(cut(input,2));
}

for ( int i = 0; i < output.size(); ++i ) {
cout << output[i] << endl;
}
}
    • good
    • 0
この回答へのお礼

参考になりました。

お礼日時:2012/04/24 09:17

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!

このQ&Aを見た人はこんなQ&Aも見ています


おすすめ情報