HOWTO · C++
C++ で文字列を Char 配列に変換する方法
この記事では、C++ で文字列を char 配列に変換する複数の方法を紹介します。
このページの内容
この記事では、文字列を Char の配列に変換するための複数のメソッドを紹介します。
文字列を Char 配列に変換するには std::basic_string::c_str メソッドを使用する
このバージョンは上記の問題を解決する C++ の方法です。これは string クラスの組み込みメソッド c_str を利用しており、ヌル文字で終端する文字配列へのポインタを返します。
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl using std::string;
int main() {
string tmp_string = "This will be converted to char*";
auto c_string = tmp_string.c_str();
cout << c_string << endl;
return EXIT_SUCCESS;
}
出力:
This will be converted to char*
c_str() メソッドが返すポインタに格納されているデータを変更したい場合は、まず memove 関数を使ってその範囲を別の場所にコピーしてから、以下のように文字列を操作する必要があります。
#include <cstring>
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl using std::string;
int main() {
string tmp_string = "This will be converted to char*";
char *c_string_copy = new char[tmp_string.length() + 1];
memmove(c_string_copy, tmp_string.c_str(), tmp_string.length());
/* do operations on c_string_copy here */
cout << c_string_copy;
delete[] c_string_copy;
return EXIT_SUCCESS;
}
なお、c_string のデータをコピーするには、以下のように様々な関数を利用することができます。ただし、マニュアルページを読み、それらのエッジケースやバグを注意深く考慮することに注意してください。
文字列を Char 配列に変換するには std::vector コンテナを使用する
もう一つの方法は、string の文字を vector コンテナに格納し、その強力なビルトインメソッドを使ってデータを安全に操作することです。
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;
int main() {
string tmp_string = "This will be converted to char*\n";
vector<char> vec_str(tmp_string.begin(), tmp_string.end());
std::copy(vec_str.begin(), vec_str.end(),
std::ostream_iterator<char>(cout, ""));
return EXIT_SUCCESS;
}
ポインタ操作を使って文字列を Char 配列に変換する
このバージョンでは、char ポインタを tmp_ptr という名前で定義し、tmp_string の最初の文字のアドレスをこれに代入しています。
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl using std::string;
int main() {
string tmp_string = "This will be converted to char*\n";
string mod_string = "I've been overwritten";
char *tmp_ptr = &tmp_string[0];
cout << tmp_ptr;
return EXIT_SUCCESS;
}
ただし、tmp_ptr のデータを変更すると tmp_string の値も変更されることに注意してください。
#include <cstring>
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl using std::string;
int main() {
string tmp_string = "This will be converted to char*\n";
string mod_string = "I've been overwritten";
char *tmp_ptr = &tmp_string[0];
memmove(tmp_ptr, mod_string.c_str(), mod_string.length());
cout << tmp_string;
return EXIT_SUCCESS;
}