2012-07-20 2 views
1

나는 boost : using 문자열 없이을 사용하지 않는 가장 좋은 방법과 가장 쉬운 방법을 알고있을 것이다.C++에서 std :: string을 에뮬레이션하는 방법은 무엇입니까?

"a b c d e f g" 

는 '\의 t을'가정이 문자열

" a b   c d  e '\t' f  '\t'g" 

변환하는 방법 exemple 들어

정상적인 표입니다.

감사합니다.

+18

* epur * 란 무엇입니까? – Praetorian

+0

"epur"의 의미를 모르겠습니다. 설명해 주시겠습니까? –

+0

Google에서 해당 단어에 관한 Nuffink. – chris

답변

2

당신은 무엇을 'epur'수단을 정의하지 않습니다하지만 예제는 당신이 최고의 제거하고 원하는처럼 보이게 공백 및 내부 교체 (및 후행?) 단일 공백이있는 공백. 이제 std :: replace_if, std :: uniqiue 및 std :: copy_if의 조합을 사용하여이 작업을 수행 할 수 있습니다. 그러나 이는 매우 복잡하며 데이터 복사를 여러 번 끝냅니다. 제자리에서 단일 패스로 처리하려면 다음과 같이 간단한 루프가 가장 좋습니다.

void epur(std::string &s) 
{ 
    bool space = false; 
    auto p = s.begin(); 
    for (auto ch : s) 
    if (std::isspace(ch)) { 
     space = p != s.begin(); 
    } else { 
     if (space) *p++ = ' '; 
     *p++ = ch; 
     space = false; } 
    s.erase(p, s.end()); 
} 
0

문자열에서 \t자를 삭제하려고합니다.

#include <iostream> 
#include <string> 
#include <algorithm> 
#include <iterator> 

int main() 
{ 
    std::string s1("a b c \t d e f \t"); 
    std::string s2; 

    std::copy_if(std::begin(s1), 
       std::end(s1), 
       std::back_inserter<std::string>(s2), 
       [](std::string::value_type c) { 
        return c != '\t'; 
       }); 

    std::cout << "Before: \"" << s1 << "\"\n"; 
    std::cout << "After: \"" << s2 << "\"\n"; 
} 

출력 : 당신은 문자열에서 모든 공백을 제거하려면

Before: "a b c d e f " 
After: "a b c d e f " 

,

return !std::isspace(c); 
으로 return 문을 대체 할 다음과 같이 \t없는 문자를 복사하여이 작업을 수행 할 수 있습니다

(isspace은 헤더에 있습니다. cctype)

6

게으른 솔루션을 사용하여 문자열 스트림 :

#include <string> 
#include <sstream> 

std::istringstream iss(" a b c d e \t f \tg"); 
std::string w, result; 

if (iss >> w) { result += w; } 
while (iss >> w) { result += ' ' + w; } 

// now use `result` 
관련 문제