Advertisement
HjHimansh

Word Processor - Google

Aug 6th, 2020
2,545
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. using namespace std;
  5.  
  6.  
  7. vector<string> breakParagraph(string paragraph, int n) {
  8.    vector<string> result;
  9.    int nP = paragraph.size();
  10.     if(nP == 0)
  11.       return {};
  12.  
  13.     if(nP <= n) {
  14.       return {paragraph};
  15.     }
  16.  
  17.   int startIndex = 0;
  18.   int endIndex = 0;
  19.   while(startIndex < nP) {
  20.     //startIndex points to wehre we have to start from
  21.     if(nP - startIndex <= n){
  22.       result.push_back(paragraph.substr(startIndex, nP-startIndex));
  23.       break;
  24.     }
  25.     endIndex = startIndex;
  26.     int spaceEncounteredIndex = -1;
  27.     while(endIndex - startIndex + 1 <= n){
  28.       if(paragraph[endIndex] == ' '){
  29.         spaceEncounteredIndex = endIndex;
  30.       }
  31.       endIndex++;
  32.     }
  33.    
  34.    
  35.     if(paragraph[endIndex] == ' '){
  36.       result.push_back(paragraph.substr(startIndex, endIndex-startIndex+1));
  37.       startIndex = endIndex + 1;
  38.       continue;
  39.     }
  40.    
  41.     //now we have traversed n letters
  42.     if(spaceEncounteredIndex == -1){
  43.       //i.e we haven't encountered any space
  44.       while(endIndex < paragraph.size() || endIndex != ' '){
  45.         endIndex++;
  46.       }
  47.       if(endIndex < paragraph.size()){
  48.         //i.e we have encountereed space
  49.         result.push_back(paragraph.substr(startIndex, endIndex-startIndex));
  50.         startIndex = endIndex + 1;
  51.         continue;
  52.       }
  53.       result.push_back(paragraph.substr(startIndex, endIndex-startIndex));
  54.       startIndex = endIndex;
  55.     }
  56.     else{
  57.       result.push_back(paragraph.substr(startIndex, spaceEncounteredIndex-startIndex+1));
  58.       startIndex = spaceEncounteredIndex+1;
  59.     }
  60.    
  61.   }
  62.    
  63.    return result;
  64. }
  65.  
  66. int main(){
  67.   string str = "I am going to the market";
  68.   vector<string> answer = breakParagraph(str, 5);
  69.  
  70.   for(auto& x : answer) {
  71.     cout << x << endl;
  72.   }
  73.  
  74.   return 0;
  75. }
  76.  
Advertisement
RAW Paste Data Copied
Advertisement