2012-05-11 3 views
1

부스트를 사용하여 문장의 각 단어의 첫 글자를 대문자로 쓰는 방법을 찾고있었습니다. 코드를 일관성있게 만드는 것, 즉 최종 문장은 입력 문장에 공백이나 탭이 없을 것입니다. 개별 단어를 얻으려면 boost :: alogrithm :: split을 사용하고 boost :: algorithm :: join을 다시 결합합니다. 첫 글자를 대문자로 입력하는 방법은 무엇입니까? 부스트 라이브러리를 사용하여 문장의 각 단어의 첫 글자를 대문자로 바꾸십시오.

나는 문제는 당신이 문장이 무엇인지를 결정하는 방법을 정의하는 것입니다이 코드를

#include <iostream>                
#include <vector>                 
#include <boost/algorithm/string/split.hpp>          
#include <boost/algorithm/string.hpp> 

int main()                  
{                    
    using namespace std;               

    string str("cONtainS   SoMe CApiTaL WORDS");      

    vector<string> strVec;              
    using boost::is_any_of;              
    using boost::algorithm::token_compress_on;         

    boost::algorithm::split(strVec, str, is_any_of("\t "), token_compress_on); 

    vector<string>::iterator i ;             

    for(i = strVec.begin() ; i != strVec.end(); i++)        
    { 
     (*i)[0] = boost::to_upper((*i)[0]); 
     cout<<*i<<endl;                
    }                   

    return 0;                 
}  
+0

우리는 ASCII를 사용하고 있습니까, 아니면 유니 코드와 호환 가능합니까? (힌트 : 부스트는 내가 아는 한 유니 코드를 지원하지 않는다.) –

+0

현재 ASCII만을 고려하고있다. 하지만 나중에 유니 코드 지원이 필요할 것입니다. –

+0

유니 코드의 경우 실제로는 단어를 대문자로 사용하기 위해 ICU와 같은 유니 코드 인식 라이브러리가 필요합니다. 따라서 분할 + 결합 전략은 현재 비용이 많이 들고 장기적으로는 효과가 있습니다. –

답변

0

이 코드는 나를 여기

#include <iostream> 
#include <boost/algorithm/string.hpp> 
#include <boost/algorithm/string/trim.hpp> 
#include <vector> 
#include <ctype.h> 

int main() 
{ 
    using namespace std; 

    string str("contAins Some  CapItal WORDS"); 
    string result; 

    vector<string> strVec; 

    using boost::is_any_of; 
    using boost::algorithm::token_compress_on; 

    boost::algorithm::split(strVec, str, is_any_of("\t "), token_compress_on); 

    vector<string>::iterator i; 

    for(i = strVec.begin(); i !=strVec.end(); ++i) 
    {                     

     boost::to_lower(*i); 
     (*i)[0]=toupper((*i)[0]); 

     cout<<(*i)<<endl; 
     result += *i +" "; 
    } 

    boost::trim_right(result); 
    cout<<result; 
    return 0; 
} 
+0

내가 알아 낸 문제는 boost :: to_upper() 필요성입니다. 값이 아닌 주소를 지정하십시오. –

2

을 시도했다. 가장 간단한 해결책은 일반 표현 "[.!?][\"\']*"으로 끝나는 시퀀스입니다 (흰색 공간을 이미 제거 했으므로). 이것은 실제로 당신이 정규식없이 없이 그것을 할 수있을만큼 간단합니다. 그런 다음 당신이 그것을 본 적이 있음을 기억하고, 에게 다음 단어를 활용 :이 부스트를 사용하지 않는 것을 이해할

bool 
isSentenceEnd(char ch) 
{ 
    return ch == '.' || ch == '!' || ch == '?'; 
} 
+0

안녕하세요, 답장을 보내 주셔서 감사합니다 :). 코드가 조금 복잡해 보입니다 : P. 나는 약간의 히트와 흔적을했고, 일하게했다. 어떤 실수라도 발견하면 저에게 말해주십시오. 코드를 읽은 후 –

+0

내 코드에서 'toupper'를 사용했습니다. 'boost :: to_lower (* i); (* i) [0] = toupper ((* i) [0]); ' 이제 올바른 출력을 내고 있습니다. 나는 100 점이 안되기 때문에 8 시간 전에 해결책을 붙여 넣을 수 없다. P –

+0

@VickeyVerma 자연 언어 (글이나 말)를 다루는 것은 복잡 할 것이다 :-). "대문자"가 의미하는 것을 정의하는 것은 국제 환경에서 사소하지 않습니다. 아마도 여기에서 유니 코드가 대문자가 아닌 대문자라고 부르는 것이 있습니다. (그리고 FWIW : 내가 게시 한 코드에 버그가 있습니다. toupper의 인수는 unsigned char로 캐스팅되어야합니다. 그렇지 않으면 정의되지 않은 동작이 발생할 수 있습니다.) –

1

:

bool atEndOfSentence = true; 
for (std::vector<std::string>::const_iterator current = words.begin(); 
     current != words.end(); 
     ++ current) { 
    if (atEndOfSentence) { 
     (*current)[0] == toupper((*current)[0]); 
    } 
    std::cout << *current << std::endl; 
    atEndOfSentence = isSentenceEnd( 
      *std::find_if(current->rbegin(), current->rend(), 
          IsNotQuoteChar()).base()); 
} 

과 :

struct IsNotQuoteChar 
{ 
    bool operator()(char ch) const 
    { 
     return ch != '\'' and ch != '\"'; 
    } 
}; 

과 유니 코드와는 작동하지 않지만 표준 라이브러리 기능을 사용하는 기본 솔루션을 제공합니다. 나는 단어의 한계를 없애기 위해 isalpha을 깨고있다. 아마도없는 가장 좋은 방법은, 그러나 그것은 단지 대안이다 :

#include <string> 
#include <iostream> 

using namespace std; 

int main() 
{ 
    string str(" cONtainS   SoMe CApiTaL WORDS"); 

    bool niw(true); 
    string strC; 
    for (size_t i = 0; i < str.size(); ++i) 
    { 
     if (niw && isalpha(str[i])) 
     { 
      strC += toupper(str[i]); 
      niw = false; 
     } 
     else if (! niw) 
     { 
      if (isalpha(str[i])) 
       strC += tolower(str[i]); 
      else 
      { 
       niw = true; 
       strC += str[i]; 
      } 
     } 
     else 
      strC += str[i]; 
    } 

    cout << str << endl; 
    cout << strC << endl; 
} 
0

작업 받고 있습니다 경우 누군가 내 C++ (11) 솔루션은 관심 :

std::string s("some lowercase string"); 
s[0] = toupper(s[0]); 
std::transform(s.begin()+1, s.end(),s.begin(),s.begin()+1, 
[](const char& a, const char& b) -> char 
{ 
    if(b==' ' || b=='\t') 
    { 
     return toupper(a); 
    } 
    return a; 
}); 
관련 문제