C++の文字列操作


このエントリーをはてなブックマークに追加

以下、すべて

#include <sstream>
#include <iostream>
using namespace std;

と書いてあるものとする。

数字から文字列へ変換

int i = 10;
ostringstream sout;
sout << i;
string s = sout.str();
cout << s << endl;

文字列から数字へ変換

string str = "123.456";
istringstream sin(str);
double num;
sin >> num;
cout << num << endl;

文字列のフォーマット

ostringstream sout;
sout << "value is " << 100;
string formatString;
formatString = sout.str();
cout << formatString << endl;

文字列を空白でSplit

string str = "abc def";
istringstream sin(str);
string s1, s2;
sin >> s1 >> s2;
cout << s1 << ", " << s2 << endl;

文字列を任意の1文字でSplit

C++1xやboostを除くと、スマートな方法はなさそう。
How to split a string in C++? - Stack Overflowで紹介されていた以下のコードはうまく動いてくれた。

std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
    std::stringstream ss(s);
    std::string item;
    while(std::getline(ss, item, delim)) {
        elems.push_back(item);
    }
    return elems;
}

std::vector<std::string> split(const std::string &s, char delim) {
    std::vector<std::string> elems;
    return split(s, delim, elems);
}

int main(void){
    string str = "abc/def/ghi";
    vector<string> substrs = split(str, '/');
    for(int i = 0; i < (int)substrs.size(); ++i){
        cout << substrs[i] << endl;
    }
    return 0;
}

文字列を任意の文字列でSplit (途中)

C++でsplit関数 - 役立たずのプログラマーブログで紹介されていたコードを以下に転載。手元で試したが、引数のcが1文字の場合はうまくいくが、2文字以上の場合は失敗しているようなので要再調査。

typedef vector<string> VS;
VS split( string s, string c )
{
	VS ret;
	for( int i=0, n; i <= s.length(); i=n+1 ){

		n = s.find_first_of( c, i );
		if( n == string::npos ) n = s.length();
		string tmp = s.substr( i, n-i );
		ret.push_back(tmp);
	}
	return ret;
}

istringstream, ostringstream

上記のコードで出てきたistringstream, ostringstreamの代わりにstringstreamを使うことも可能。しかし、意図をはっきりさせるためにはistringstreamまたはostringstreamを使うのがよさそう。