2012-12-14 2 views
2
내 문자열의 문자열을 제거 할

, 그것은 다음과 같은 :지우개로 "("에서 ")"까지 std :: string의 문자를 제거 하시겠습니까?

At(Robot,Room3) 

또는

나는에서 모든 문자를 제거하는 방법
SwitchOn(Room2) 

또는

SwitchOff(Room1) 

왼쪽 대괄호 ( 오른쪽 대괄호 ), 색인을 모르겠습니까?

+0

이 중첩 될 수 있습니다 괄호 – Shahbaz

+0

@Shahbaz : 아니요, 단 하나의'('와 단일')'. – ron

+1

[string :: find] (http://en.cppreference.com/w/cpp/string/basic_string/find)에 익숙합니까? – Shahbaz

답변

6

당신이 문자열이 당신이 할 수있는 패턴과 일치 알고있는 경우 :

std::string str = "At(Robot,Room3)"; 
str.erase(str.begin() + str.find_first_of("("), 
      str.begin() + str.find_last_of(")")); 

또는 당신이 원하는 경우 안전

auto begin = str.find_first_of("("); 
auto end = str.find_last_of(")"); 
if (std::string::npos!=begin && std::string::npos!=end && begin <= end) 
    str.erase(begin, end-begin); 
else 
    report error... 

또한 표준 라이브러리 <regex>를 사용할 수 있습니다.

std::string str = "At(Robot,Room3)"; 
str = std::regex_replace(str, std::regex("([^(]*)\\([^)]*\\)(.*)"), "$1$2"); 
+0

'1st' 제안은 훌륭합니다! +1을 선택했습니다. – ron

+1

작동하지만, 동일한 범위를 두 번 탐색하기 때문에'hugestring (tiny)'라고 말하면 조금 비효율적입니다. –

+0

@KerrekSB는 'find_last_of'로 전환되었지만 여전히 비효율적 일 수 있습니다. '작은 (작은) hugestring'. – bames53

2

컴파일러와 표준 라이브러리가 충분히 새로운 경우 std::regex_replace을 사용할 수 있습니다.

그렇지 않으면 먼저 '('을 검색하고 마지막으로 ')'을 역 검색 한 다음 std::string::erase을 사용하여 그 사이의 모든 항목을 제거합니다. 또는 닫는 괄호 뒤에 아무 것도 없을 경우 첫 번째 문자열을 찾고 std::string::substr을 사용하여 보관하려는 문자열을 추출하십시오.

은 당신이 가지고있는 문제는 실제로 괄호를 사용 std::string::find 및/또는 std::string::rfind을 찾는 경우.

1

당신은 후에 'str.length() - 1'될 때까지 '('다음 삭제 첫 번째를 검색 할 수 있습니다 (두 번째 브래킷) 마지막에 항상

1

간단한 하고 안전한 가정 효율적인 솔루션 :.?

std::string str = "At(Robot,Room3)"; 

size_t const open = str.find('('); 
assert(open != std::string::npos && "Could not find opening parenthesis"); 

size_t const close = std.find(')', open); 
assert(open != std::string::npos && "Could not find closing parenthesis"); 

str.erase(str.begin() + open, str.begin() + close); 

이 잘못 형성 입력 조심, 한 번 이상 문자를 해석하지 마십시오

관련 문제