Hello
In a project I am going to have to access files where data is stored as values separated by a delimiter character.
I am essentially trying to imitate the PHP explode() function (
http://php.net/manual/en/function.explode.php), in that it would take a string given to it, and a delimiter character, and break up the string in its parts, broken up at the delimiter character, then save all the parts as an array.
I have managed to do this in the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
|
#include <iostream>
#include <string>
using namespace std;
int main()
{
//Declare variables
string instring; //Main Input
string word; //Temporary words in Array generation
int wordcount = 0; //Counter for Array generation
int splitcount = 0; //Number of Splitmarks
char sepchar = '_'; //character to look for in string splitting
//Getting the string
cout << "Input String: ";
cin >> instring;
cout << endl << "Broken up with symobl \"" << sepchar << "\" gives the following:" << endl << endl;
//Finding Number of Splitmarks
for(int i = 0; i < instring.length(); i++)
{ char ch = instring[i];
if (ch == sepchar)
{ splitcount++;}}
//Cleaning string (adding spechar if needed)
if (instring[instring.length()-1] != sepchar)
{instring.append(1,sepchar);
splitcount++;}
//declaring Array
string values [splitcount];
//Generate Array
for(int i = 0; i < instring.length(); i++)
{
char ch = instring[i];
if (ch != sepchar)
{
word.append(1,ch);
}else{
values[wordcount] = word;
word="";
wordcount++;
}
}
//Printing Array
for(int i=0;i<(splitcount);i++)
{cout << values[i] << endl;}
cout << endl << endl;
main();
return 0;
}
|
However, I want to use this as a called-on function. At first, I thought of having something like
string results [??] = split(string);
But then I realised that I did not know the size of the array.
So I thought maybe I could have a different function to compute the array size, and then use that, but it seems to be very heavy for nothing.
Is there a more elegant solution?
It would be very important that I could decide the name of the resulting array.