目的:
把一个带逗号的字符串比如“”aa,bbb,cc,dd“”分成四个小的字符串,作为一个数组返回
#include <iostream>
#include <string>
using namespace std;
string* split(string input) //1. 要返回string * 类型的结果
{
string *temp;
temp=new string[4]; // 2. 用这两行设置一个string* 类型的数组作为返回值
int j = 0;
for (unsigned i = 0; i < input.length(); i++)
{
if (input[i] != ',')
temp[j] += input[i];
else
j++;
}
return temp; //3. 返回值为string*型的
}
int main()
{
string fullstring = "aa,bbb,cc,ddd";
string *output; //4. 不仅函数里要用string*类型的变量,main里也要有string*类型的变量,它不用是数组
output = split(fullstring); //5. 输出返回值
for (int j = 0; j <4; j++)
cout << output[j] << " "; // 6. 打印返回值数组
cout << endl;
system("pause");
return EXIT_SUCCESS;
}
编程收获:
因为c++不允许直接把数组作为返回值,所以返回一个指针类型的数组
要分别改动split函数和main,在其中分别建立string*类型的变量。
注意:不是在两个函数里,简单的都做成string*类型的数组,
具体改动,见备注的6个步骤
运行结果如图: