Hey,
My name is Corey, I've been doing programming off and on as a hobby over the last 10 years or so.
I needed to do a string operation in C++ to separate parts of the string based on a delimiter into an array
Example in VBA, return an array {"Hello", "World"}
Split("Hello World", " ")
I attempted doing this in C++ that would give an equivalent output, but I have a question about how i'm handling the New operator.
I created a pointer ss in my main function, then
In another function I create another pointer result
In the function I use the New operator to create a dynamic array then return the pointer.
back in my main I overload the ss pointer with the pointer returned from the split function.
In my Main, I delete[] the ss pointer
Is this enough, am I creating a memory leak?
I know somebody is going to point out that I should being using a vector for this type of thing. But I’m more interested in how to handle overloading in these sistuations.
As for resolve any doubts of a memory leak, I’ll simply reference the pointer ss from my main to the function instead.
The code I'm using to delimit a string:
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
|
#include <iostream>
#include <string>
using namespace std;
string* split (string str, string delimiter, int &numFound) {
// seperate string into each time delimiter character is found
size_t pos = 0;
int num = 1;
string s = str;
string* result;
// pre-pass get number of seperations
while ((pos = s.find(delimiter)) != string::npos) {
s.erase(0, pos + delimiter.length());
num++;
}
numFound = num;
// if pre-pass, then create array
if (numFound > 0) {
num = 0;
s = str;
result = new string[numFound];
while ((pos = s.find(delimiter)) != string::npos) {
result[num] = s.substr(0, pos);
s.erase(0, pos + delimiter.length());
num++;
}
result[num] = s.substr(0, pos);
}
// return array
return result;
}
int main() {
string* ss; // String Stream Array
int sc = 0; // String Stream Array Count
ss = split("Hello World", " ", sc);
if (sc > 0) {
for (int i = 0; i < sc; i++){
cout << ss[i] << endl;
}
}
delete[] ss;
}
|