Answer the question
In order to leave comments, you need to log in
How to write explode() in c++?
I just started writing in C ++, I decided to start by writing a function, but I don’t understand how everything is very crooked, I didn’t have so many errors with any language. Please help me understand what I'm doing wrong here. The explode() function in PHP cuts a string at a delimiter.
#include <iostream>
#include <vector>
#include <string>
vector<string> explode(string separator, string input){
string line;
int count = 1;
vector<string> output {};
for (int i = 0; input[i] != '\0'; ++i) {
if (input[i] == separator) {
output.push_back(line);
line = "";
count++;
} else {
line += input[i];
}
}
return output;
}
int main(){
int count = 1;
vector<string> msg = explode(".", "a.b.c.d");
for (const string& word : msg){
cout << count << " => " << word << endl;
count++;
}
return 0;
}
Answer the question
In order to leave comments, you need to log in
Here is a function for delimiter with any number of characters:
std::vector<std::string> explode(std::string separator, std::string input) {
std::vector<std::string> vec;
for(int i{0}; i < input.length(); ++i) {
int pos = input.find(separator, i);
if(pos < 0) { vec.push_back(input.substr(i)); break; }
int count = pos - i;
vec.push_back(input.substr(i, count));
i = pos + separator.length() - 1;
}
return vec;
}
Add using namespace std;
after headers (although of course it's better to explicitly write std::vector, std:string).
You input[i] != '\0'
shouldn't do this, because, if I'm not mistaken, the pluses no longer guarantee the presence of a terminator at the end of the line, and in any case, this will be an appeal beyond the length of the line, which is Undefined behavior.
Your code does not add the last piece of the string to the array.
In PHP separator can consist of several characters, in yours - of one. Here you need something like string::find() to use to find a substring.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question