Stringstream을 사용하여 문자열에서 공백 제거

문자열에서 공백을 제거하는 솔루션이 이미 게시되었습니다. 여기 . 이 기사에서는 다음을 사용하는 또 다른 솔루션 문자열 스트림 논의된다.

연산:  

1. Enter the whole string into stringstream. 2. Empty the string. 3. Extract word by word and concatenate to the string. 

프로그램 1: 사용 EOF . 

CPP
   // C++ program to remove spaces using stringstream   #include          using     namespace     std  ;   // Function to remove spaces   string     removeSpaces  (  string     str  )   {      stringstream     ss  ;      string     temp  ;      // Storing the whole string      // into string stream      ss      < <     str  ;      // Making the string empty      str     =     ''  ;      // Running loop till end of stream      while     (  !  ss  .  eof  ())     {      // Extracting word by word from stream      ss     >>     temp  ;      // Concatenating in the string to be      // returned      str     =     str     +     temp  ;      }      return     str  ;   }   // Driver function   int     main  ()   {      // Sample Inputs      string     s     =     'This is a test'  ;      cout      < <     removeSpaces  (  s  )      < <     endl  ;      s     =     'geeks for geeks'  ;      cout      < <     removeSpaces  (  s  )      < <     endl  ;      s     =     'geeks quiz is awesome!'  ;      cout      < <     removeSpaces  (  s  )      < <     endl  ;      s     =     'I love to code'  ;      cout      < <     removeSpaces  (  s  )      < <     endl  ;      return     0  ;   }   

산출
Thisisatest geeksforgeeks geeksquizisawesome! Ilovetocode 

시간 복잡도: O(n) 여기서 n은 문자열의 길이입니다.
보조 공간: 에)

프로그램 2: 사용 getline() . 

CPP
   // C++ program to remove spaces using stringstream   // and getline()   #include          using     namespace     std  ;   // Function to remove spaces   string     removeSpaces  (  string     str  )   {      // Storing the whole string      // into string stream      stringstream     ss  (  str  );      string     temp  ;      // Making the string empty      str     =     ''  ;      // Running loop till end of stream      // and getting every word      while     (  getline  (  ss       temp       ' '  ))     {      // Concatenating in the string      // to be returned      str     =     str     +     temp  ;      }      return     str  ;   }   // Driver function   int     main  ()   {      // Sample Inputs      string     s     =     'This is a test'  ;      cout      < <     removeSpaces  (  s  )      < <     endl  ;      s     =     'geeks for geeks'  ;      cout      < <     removeSpaces  (  s  )      < <     endl  ;      s     =     'geeks quiz is awesome!'  ;      cout      < <     removeSpaces  (  s  )      < <     endl  ;      s     =     'I love to code'  ;      cout      < <     removeSpaces  (  s  )      < <     endl  ;      return     0  ;   }   // Code contributed by saychakr13   

산출
Thisisatest geeksforgeeks geeksquizisawesome! Ilovetocode 

시간 복잡도: O(n) 
보조 공간: O(n)