Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <string>
- using namespace std;
- vector<string> breakParagraph(string paragraph, int n) {
- vector<string> result;
- int nP = paragraph.size();
- if(nP == 0)
- return {};
- if(nP <= n) {
- return {paragraph};
- }
- int startIndex = 0;
- int endIndex = 0;
- while(startIndex < nP) {
- //startIndex points to wehre we have to start from
- if(nP - startIndex <= n){
- result.push_back(paragraph.substr(startIndex, nP-startIndex));
- break;
- }
- endIndex = startIndex;
- int spaceEncounteredIndex = -1;
- while(endIndex - startIndex + 1 <= n){
- if(paragraph[endIndex] == ' '){
- spaceEncounteredIndex = endIndex;
- }
- endIndex++;
- }
- if(paragraph[endIndex] == ' '){
- result.push_back(paragraph.substr(startIndex, endIndex-startIndex+1));
- startIndex = endIndex + 1;
- continue;
- }
- //now we have traversed n letters
- if(spaceEncounteredIndex == -1){
- //i.e we haven't encountered any space
- while(endIndex < paragraph.size() || endIndex != ' '){
- endIndex++;
- }
- if(endIndex < paragraph.size()){
- //i.e we have encountereed space
- result.push_back(paragraph.substr(startIndex, endIndex-startIndex));
- startIndex = endIndex + 1;
- continue;
- }
- result.push_back(paragraph.substr(startIndex, endIndex-startIndex));
- startIndex = endIndex;
- }
- else{
- result.push_back(paragraph.substr(startIndex, spaceEncounteredIndex-startIndex+1));
- startIndex = spaceEncounteredIndex+1;
- }
- }
- return result;
- }
- int main(){
- string str = "I am going to the market";
- vector<string> answer = breakParagraph(str, 5);
- for(auto& x : answer) {
- cout << x << endl;
- }
- return 0;
- }
Advertisement
RAW Paste Data
Copied
Advertisement