LoginSignup
4
4

More than 5 years have passed since last update.

std::string は文字列中の'\0'を許す

Posted at

知らない人が少なくないみたいだけど、
std::string/std::wstring 文字列中に '\0' / L'\0' を含んでいてもかまわない。
要は単なるchar/wchar_t列なわけで、バッファとして利用可能。

#include <iostream>
#include <string>
#include <cassert>

using namespace std;

int main() {
  string hw = "hello";
  hw += '\0';
  hw += "world";
  // string hw("hello\0world", 11) も可。

  assert( hw.size() == 11 );

  cout << '[';
  for ( char ch : hw ) cout << (ch == '\0' ? '_' : ch);
  cout << "]\n";

  // '\0' を境に切り分ける
  string::size_type nullpos = hw.find('\0');
  cout << '[' << hw.substr(0, nullpos) << ']'
       << '[' << hw.substr(nullpos+1)  << ']'
       << endl;
}
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4