2014-04-13 4 views
-1

문자열이 abcdef 인 경우 bcdef을 얻는 방법은 무엇입니까? 시도했지만문자열의 첫 번째 문자가 포함되지 않은 하위 문자열 얻기

cout << str.substr(1,'\0')<< endl; 

그러나 작동하지 않았습니다.

문자 배열은 어떻습니까?

+2

substr을 사용하면 해당 문자열에서 'g'를 얻을 수 없습니다. –

+2

''bcdefg ''는 ** "abcdef"'의 하위 문자열이 아닙니다. – pmg

+0

나는 그것을 고쳤다. 덕분에 – user3239138

답변

0

substr(position, length)position 색인에서 시작하여 length 문자로 끝나는 문자열을 position 다음에 반환합니다.

\0을 문자열 인덱스의 끝으로 변경하거나 두 번째 매개 변수가없는 경우 나머지 문자열을 반환하기 때문에 기본적으로 아무것도 변경하지 않아야합니다.

str.substr(1)bcdef

str.substr(1, 5) 또한 bcdef

2
#include <iostream> 
using namespace std; 

int main() { 

    std::string str = "abcdef"; 
    cout << str.substr (1); 

    return 0; 
} 

라이브를 시도 반환 반환 : 당신이 문자열에 대한 설명서를 살펴 경우 http://ideone.com/AueOXR

: SUBSTR :

string substr (size_t pos = 0, size_t len = npos) const; 

Generate substring 
Returns a newly constructed string object with its value initialized to a copy of a substring of this object. 

The substring is the portion of the object that starts at character position pos and spans len characters (or until the end of the string, whichever comes first). 

http://www.cplusplus.com/reference/string/string/substr/

즉, 두 번째 매개 변수를 지정하지 않으면 문자열 끝에있는 기본 매개 변수로 간주됩니다.

1

다른 방법

std::cout << str.substr(1) << std::endl; 

: 그것은 간단하게 내가 더 효과적 생각하면 문자열이 포함 된 제로

std::cout << str.c_str() + 1 << std::endl; 
2

을 포함하지 않는 경우 시도 멤버 함수 c_str을 사용하는 것입니다

cout << str.substr(1)<< endl; 

물론 문자열의 문서는 당신이 알 필요가있는 모든 것을 알려줍니다 ...

관련 문제