1. 程式人生 > >C++使用空格或者特定字元 分割字串string

C++使用空格或者特定字元 分割字串string

請看程式碼示例, 複製貼上,執行即可,使用其他字元做分割,則 用該 字元 替換 strtok 函式 第二個引數 即可

// strings and c-strings
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int main ()
{
  std::string str ("Please split this  sentence into  tokens");

  char * cstr = new char [str.length()+1];
  std::strcpy (cstr, str.c_str());

  // cstr now contains a c-string copy of str

  char * p = std::strtok (cstr," ");
  cout<<p<<endl;
  while (p!=0)
  {
    std::cout << p << '\n';
    p = std::strtok(NULL," ");
  }

  delete[] cstr;
  return 0;
}