I am trying to create a function that will take in a long string with " " and "," dividing different elements gained from a text file. "," represents a new line and " " represents the end of a number in the line. once split the strings should be part of an array.
string* splitstr(string text, string deli = " ")
{
int start = 0;
int end = text.find(deli);
string *numbers[end];
for (int i = 0; end != -1; i++)
{
numbers[i] = text.substr(start, end - start);
start = end + deli.size();
end = text.find(deli, start);
}
return numbers;
}
However I am facing a problem where I get this:
cannot convert 'std::string**' {aka 'std::__cxx11::basic_string<char>**'} to 'std::string*' {aka 'std::__cxx11::basic_string<char>*'} in return
How can I resolve this, or improve my function?
I was expecting to be able to store string elements in a string array and make the function return the array. I’m fairly new to programming and I started off with java so this logic might not work in c++.
>Solution :
You should avoid using arrays like this and instead use a vector
like as follows:
std::vector<std::string> splitstr(const std::string & text, const std::string & deli = " ")
{
int start = 0;
int end = text.find(deli);
std::vector<std::string> numbers;
for (int i = 0; end != -1; i++)
{
numbers.push_back(text.substr(start, end - start));
start = end + deli.size();
end = text.find(deli, start);
}
return numbers;
}
note this will not get the last item in the string if there is not a delimiter after it.