Wednesday, May 15, 2013

Remove space from string C++

Write a function that removes extra spaces from a string and leaves only one correct space.


  1. void removespace(string &s){  
  2.   
  3.   int count = 0;   
  4.   
  5.   string buffer;  
  6.   
  7.   for(int i = 0; i < s.length(); i++){  
  8.   
  9.     if(s[i] != ' ') {  
  10.   
  11.          count = 0;  
  12.   
  13.          buffer.push_back(s[i]);  
  14.     }  
  15.     else{  
  16.   
  17.        if(count == 0) {  
  18.   
  19.           count++;  
  20.   
  21.           buffer.push_back(' ');  
  22.        }  
  23.    }  
  24.   }   
  25.  s = buffer;  
  26. }   

No comments:

Post a Comment