, 그것은 다음과 같은 :지우개로 "("에서 ")"까지 std :: string의 문자를 제거 하시겠습니까?
At(Robot,Room3)
또는
나는에서 모든 문자를 제거하는 방법SwitchOn(Room2)
또는
SwitchOff(Room1)
왼쪽 대괄호
(
오른쪽 대괄호
)
, 색인을 모르겠습니까?
, 그것은 다음과 같은 :지우개로 "("에서 ")"까지 std :: string의 문자를 제거 하시겠습니까?
At(Robot,Room3)
또는
나는에서 모든 문자를 제거하는 방법SwitchOn(Room2)
또는
SwitchOff(Room1)
왼쪽 대괄호
(
오른쪽 대괄호
)
, 색인을 모르겠습니까?
당신이 문자열이 당신이 할 수있는 패턴과 일치 알고있는 경우 :
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");
컴파일러와 표준 라이브러리가 충분히 새로운 경우 std::regex_replace
을 사용할 수 있습니다.
그렇지 않으면 먼저 '('
을 검색하고 마지막으로 ')'
을 역 검색 한 다음 std::string::erase
을 사용하여 그 사이의 모든 항목을 제거합니다. 또는 닫는 괄호 뒤에 아무 것도 없을 경우 첫 번째 문자열을 찾고 std::string::substr
을 사용하여 보관하려는 문자열을 추출하십시오.
std::string::find
및/또는
std::string::rfind
을 찾는 경우.
당신은 후에 'str.length() - 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);
이 잘못 형성 입력 조심, 한 번 이상 문자를 해석하지 마십시오
이 중첩 될 수 있습니다 괄호 – Shahbaz
@Shahbaz : 아니요, 단 하나의'('와 단일')'. – ron
[string :: find] (http://en.cppreference.com/w/cpp/string/basic_string/find)에 익숙합니까? – Shahbaz