fork download
  1. #include<stdio.h>
  2. #include<iostream>
  3. using namespace std;
  4.  
  5. string word_wrap(string str, int len)
  6. {
  7. int st=0;
  8. int sz=str.size();
  9. string ans;
  10.  
  11. while(st< sz)
  12. {
  13. int ed=st+len;
  14. int _end=ed < str.size() ? ed : str.size()-1;
  15.  
  16. if(_end==str.size()-1)
  17. {
  18. _end++;
  19. str[_end]='\n';
  20.  
  21. }
  22. else if(str[_end]==' ')
  23. {
  24. str[_end]='\n';
  25. _end++;
  26. }
  27. else
  28. {
  29. int ed1=_end;
  30. while(_end > st and str[_end]!=' ') _end--;
  31.  
  32. if(st!=_end)
  33. {
  34. str[_end++]='\n';
  35. }
  36. else
  37. str.insert(ed1++,1,'\n'), _end=ed1;
  38. }
  39. st=_end;
  40. }
  41. return str;
  42. }
  43.  
  44. int main()
  45. {
  46. string s="i am going to cuet";
  47. cout<<word_wrap(s,5)<<endl;
  48. }
  49.  
Success #stdin #stdout 0s 15232KB
stdin
Standard input is empty
stdout
i am
going
to
cuet