I made a header for this and you can use it to split a string into array of strings using a string as a splitter heres how:
create a file with a name "WordSplitter.h" and save it along with the folder of cpp file.
Copy paste this in WordSplitter.h:
#ifndef WORDSPLITTER_H
#undef WORDSPLITTER_H
#include <iostream>
#include <string>
using namespace std;
class Word {
public:
string word;
string list[99];
Word(string s){
word = s;
}
int size(string s){
int size = 0;
for(char c : s){
size ++;
}
return size;
}
int size(){
int size = 0;
for (char c : word){
size ++;
}
return size;
}
string slice(int start, int end){
string result = "";
for(int i = start ; i <= end ; i ++){
result += word[i];
}
return result;
}
string sliceThis(string s, int start, int end){
string result = "";
for(int i = start ; i <= end ; i ++){
result += s[i];
}
return result;
}
int count(string s){
int count, start = 0;
for(int end = size(s)-1 ; end < size() ; end ++){
if(s == slice(start,end)){count ++;}
start ++;
}
return count;
}
int listSize(){
int size_ = 0;
for(string str : list){
if (size(str) > 0){
size_ ++;
}
}
return size_;
}
void split(string splitter){
int splitSize = size(splitter) - 1;
int split_start = 0;
int split_end, end;
int index = 0;
if (count(splitter) > 0){
for(end = splitSize ; end < size() ; end ++){
int start = end - splitSize;
if (splitter == slice(start,end)){
split_end = start - 1;
list[index] = slice(split_start,split_end);
split_start = end + 1;
end += splitSize;
index ++;
}
}
list[index] = slice(split_end + size(splitter) + 1, size());
//list[index] = slice(end + 1, size());
}
}
};
#endif
- inside your cpp file:
#include <iostream>
#include <string>
#include "WordSplitter.h"
using namespace std;
int main(){
Word mySentence = Word("I[]got[]a[]jar[]of[]dirt");
mySentence.split("[]"); //use a splitter
for(int i = 0 ; i < mySentence.count("[]") + 1 ; i ++){
cout << mySentence.list[i] << endl;
}
return 0;
}
output:
I
got
a
jar
of
dirt