【问题标题】:Store a string into an array将字符串存储到数组中
【发布时间】:2016-04-05 09:48:25
【问题描述】:
我有一个字符串变量
string = "这是我的字符串"
我想将由 空格 分隔的每个单词存储到一个数组中
- array[0]="this";
- 数组[1]="是";
- 数组[2]="我的";
- 数组[3]="字符串";
【问题讨论】:
标签:
c++
arrays
string
iostream
【解决方案2】:
首先,您必须包含“sstream”类,例如:
#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;
}
【解决方案3】:
对于这种情况,可以使用字符串分隔符的概念
strtok(const char * str, int delimiter);
对于您的情况,分隔符是“空白”。
程序:
#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;
}
我们可以添加任何编号。用双引号括起来的分隔符。这就像字符串(分隔符)搜索。