将字符串存储到数组中

Store a string into an array

我有一个字符串变量

string = "这是我的字符串"

我想将由 空格 分隔的每个单词存储到数组

首先你必须包括 "sstream" class 比如:

#include <sstream>

然后使用下面的代码:

    string str= "this is my string"
    int len = str.length();
    string arr[len];
    int i = 0;
    stringstream ssin(str);
    while (ssin.good() && i < len){
        ssin >> arr[i];
        ++i;
    }
    for(i = 0; i < len; i++){
        cout << arr[i] << endl;
    }

您可以使用 std::copy with std::istringstream and std::istream_iterator and std::back_inserter:

vector<string> v;
istringstream ss(" this is my string");
copy(istream_iterator<string>(ss), istream_iterator<string>(), back_inserter(v));

LIVE

对于这种情况,您可以使用字符串分隔符概念

 strtok(const char * str, int delimiter);

对于您的情况,分隔符是 "white space"。

程序:

 #include <stdio.h>
 #include <string.h>

 int main ()
 {
     char str[] ="This a sample string";
     char * output_after_delimiter_applied;
     char *out_arr[4];
     int i=0;

     printf("The original string is %s\n", str);

     output_after_delimiter_applied = strtok (str," ");

     while (output_after_delimiter_applied != NULL)
     {
         out_arr[i] = output_after_delimiter_applied;
         output_after_delimiter_applied = strtok (NULL, " ");    
                   // NULL parameter is for continuing the search
                  //  delimiter is "white space".
         i++;
     }

     for(i=0; i < 4 ; i++)
         printf("%s\n", out_arr[i]); 

     return 0;
  }

我们可以添加任何编号。带双引号的分隔符。它就像字符串(分隔符)搜索。