サンプルコード。


#include <iostream>
#include <string>
#include <vector>
 
int main(int argc, char *argv[]){
 
  std::vector<std::string> slist;
 
  // 引数がひとつのコンストラクタ
  slist.push_back("AZ");
  slist.push_back("A\0Z");
  slist.push_back(std::string("A\0Z"));
 
  // 第二引数で文字数を指定できるコンストラクタ
  slist.push_back(std::string("A\0Z", 3));
 
  // 第二引数で文字数を指定できるコンストラクタ
  char atoz[] = {65, 0, 90};
  slist.push_back(std::string(atoz, 3));
 
  for(std::vector<std::string>::iterator it = slist.begin(); it != slist.end(); it++){
    std::string str = *it;
    std::cout << "*****" << std::endl;
    for(unsigned int i=0; i<str.size(); i++){
      char ch = str.at(i);
      std::cout << (int)ch << std::endl;
    }
  }
}

実行結果。


$ g++ ./nullsample.cpp 
$ ./a.out 
*****
65
90
*****
65
*****
65
*****
65
0
90
*****
65
0
90

std::stringのコンストラクタの第二引数に文字数を指定すれば、NULL文字「'\0'」を含んでいる文字も扱うことができる。

ちなみに環境。


$ uname -mrsv
Darwin 10.7.0 Darwin Kernel Version 10.7.0: Sat Jan 29 15:17:16 PST 2011; root:xnu-1504.9.37~1/RELEASE_I386 i386
 
$ g++ --version
i686-apple-darwin10-g++-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5664)
Copyright (C) 2007 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

NULL文字が含まれている文字列で c_str() して strlen で文字数をチェックするとかは危険。
また、UTF-16ではNULL文字と同じ値(ようするにゼロ)をもつ文字が存在するため、NULL文字を文字列の終端として扱うのは危険。

Ref. C++文字列(std::string)

tags: c++

Posted by NI-Lab. (@nilab)