2013-07-01 2 views
2

은 내가 문자열 플러스 내가 할 인쇄 할 수없는 문자의 전체 무리를 얻을 수 그러나, std::string복사 길이 : 문자열

char name[] = "Sally Magee"; 
std::string first; 
copy(name, name + 5, first.begin()); //from #include <algorithm> 
std::cout << first.c_str(); 

에 문자 배열에서 5 개 문자를 복사하려고 하지. 어떤 아이디어? 감사.

답변

8

그냥

char name[] = "Sally Magee"; 
std::string first(name, name + 5); 
std::cout << first << std::endl; 

std::string constructor 링크

+0

감사 것이다 SO가 나를 허용 할 때 받아 들여라. – user2537688

+0

@ user2537688 당신은 오신 것을 환영합니다. – billz

+0

또 다른 방법은'std :: string first (name, 5);' –

0

무엇 std::copy 알고리즘을 수행하는 각 요소 후 대상 반복자를 다른 후 하나 개의 소스 요소를 복사하고 발전하는 것입니다 보여요.

  • , 대상 컨테이너의

    • 크기 중 하나를 복사 모든 요소에 맞게 충분히 큰 설정되어 있다고 가정하거나 대상 컨테이너의 크기를 증가 반복자 유형을 사용 당신이 그것에 할당 할 때마다. 사용 a

      #include <iostream> 
      #include <string> 
      #include <algorithm> 
      
      int main() 
      { 
          char source[] = "hello world"; 
      
          std::string dest; 
          dest.resize(5); 
          std::copy(source,source+5,begin(dest)); 
      
          std::cout << dest << std::endl; 
      
          return 0; 
      } 
      
    • :

      1. 이 사본을하기 전에 문자열의 크기를 조정 : 당신이 std::copy 알고리즘을 사용하려면

    따라서이이 개 문제를 해결하는 방법이 있습니다 표준 삽입 대신 반복 삽입 반복자 :

    #include <iostream> 
    #include <string> 
    #include <algorithm> 
    #include <iterator> 
    
    int main() 
    { 
        char source[] = "hello world"; 
    
        std::string dest; 
        std::copy(source,source+5,std::back_inserter(dest)); 
    
        std::cout << dest << std::endl; 
    
        return 0; 
    } 
    
  • 목표는 적절한 생성자가 명확하게 최선의 방법입니다 사용하여, 초기화시에 문자열로 처음 5 개 문자를 복사하는 것입니다 경우, 다른 사람에 의해 지적 그러나 :

    std::string dest(source,source+5);