문제
무엇이 가장 선호하는 방법을 제거 공간에서 문자열에서는 C++?수 루프를 통해 모든 문자는 새로운 문자열을,하지만 더 나은 방법이 있을까?
해결책
최고의 것을 사용하여 알고리즘 remove_if
고 isspace:
remove_if(str.begin(), str.end(), isspace);
지금 알고리즘은 자신을 변경할 수 없습니다 컨테이너(단 값을 수정할 수 있습니다),그래서 실제로 섞은 값을 주고 포인터를 반환하는 지금 해야 합니다.그래서 우리는 전화 문자열::삭제를 실제로 수정 길이의 컨테이너:
str.erase(remove_if(str.begin(), str.end(), isspace), str.end());
우리는 또한 remove_if 만들 것입니다에서 가장 중 하나입니다.여기에 샘플을 구현:
template<typename T, typename P>
T remove_if(T beg, T end, P pred)
{
T dest = beg;
for (T itr = beg;itr != end; ++itr)
if (!pred(*itr))
*(dest++) = *itr;
return dest;
}
다른 팁
std::string::iterator end_pos = std::remove(str.begin(), str.end(), ' ');
str.erase(end_pos, str.end());
서 gamedev
string.erase(std::remove_if(string.begin(), string.end(), std::isspace), string.end());
을 사용할 수 있는 부스트 문자열 Algo? http://www.boost.org/doc/libs/1_35_0/doc/html/string_algo/usage.html#id1290573
erase_all(str, " ");
트리밍,사용 부스트 문자열을 알고리즘:
#include <boost/algorithm/string.hpp>
using namespace std;
using namespace boost;
// ...
string str1(" hello world! ");
trim(str1); // str1 == "hello world!"
당신이 사용할 수 있는 이 솔루션을 제거하기 위한 문자:
#include <algorithm>
#include <string>
using namespace std;
str.erase(remove(str.begin(), str.end(), char_to_remove), str.end());
안녕하세요,당신이 뭔가를 할 수 있습니다.이 기능을 모두 삭제합니다.
string delSpaces(string &str)
{
str.erase(std::remove(str.begin(), str.end(), ' '), str.end());
return str;
}
나는 또 다른 기능을,삭제하는 불필요한 모든 공간이 있습니다.
string delUnnecessary(string &str)
{
int size = str.length();
for(int j = 0; j<=size; j++)
{
for(int i = 0; i <=j; i++)
{
if(str[i] == ' ' && str[i+1] == ' ')
{
str.erase(str.begin() + i);
}
else if(str[0]== ' ')
{
str.erase(str.begin());
}
else if(str[i] == '\0' && str[i-1]== ' ')
{
str.erase(str.end() - 1);
}
}
}
return str;
}
string replaceinString(std::string str, std::string tofind, std::string toreplace)
{
size_t position = 0;
for ( position = str.find(tofind); position != std::string::npos; position = str.find(tofind,position) )
{
str.replace(position ,1, toreplace);
}
return(str);
}
그것을 사용:
string replace = replaceinString(thisstring, " ", "%20");
string replace2 = replaceinString(thisstring, " ", "-");
string replace3 = replaceinString(thisstring, " ", "+");
당신이 원하는 경우 이 함께하는 간편한 매크로,여기에 중 하나:
#define REMOVE_SPACES(x) x.erase(std::remove(x.begin(), x.end(), ' '), x.end())
이 있다고 가정하고 수행 #include <string>
물론입니다.
전화는 다음과 같이
std::string sName = " Example Name ";
REMOVE_SPACES(sName);
printf("%s",sName.c_str()); // requires #include <stdio.h>
내가 사용하는 아래 주변의 작업에 대한 긴-에 대한 확실하지 않도로 복잡합니다.
s.erase(std::unique(s.begin(),s.end(),[](char s,char f){return (f==' '||s==' ');}),s.end());
할 때 싶어 제자 ' '
고 몇 가지 예: -
사
s.erase(std::unique(s.begin(),s.end(),[](char s,char f){return ((f==' '||s==' ')||(f=='-'||s=='-'));}),s.end());
마찬가지로 증가 ||
는 경우 문자의 수신을 제거하지 않은 1
그러나 언급했듯이 다른 사람에 의해 삭제 제거한 관용도 괜찮습니다.
string removeSpaces(string word) {
string newWord;
for (int i = 0; i < word.length(); i++) {
if (word[i] != ' ') {
newWord += word[i];
}
}
return newWord;
}
이 코드는 기본적으로 문자열과 반복을 통해 모든 문자니다.그 다음에 여부를 확인하는 문자열은 흰색 공간,그렇지 않은 경우 다음의 문자가 추가하는 새로운 문자열입니다.
string removespace(string str)
{
int m = str.length();
int i=0;
while(i<m)
{
while(str[i] == 32)
str.erase(i,1);
i++;
}
}
나는 두려워요 그것은 최고의 솔루션을 나는 생각할 수 있습니다.그러나 사용할 수 있는 예약()에 사전에 할당할 필요한 최소한 메모리를 사전에 속도를 것이다.당신은 끝나는 새 문자열을 것입니다 아마 더 단축될 수 있지만 차지하는 동일 금액의 메모리,하지만 당신은 피 재할당 횟수.
편집:상황에 따라,이것이 부과될 수 있습 헤드보다 jumbling 문자를 주변에 있다.
당신이해야 다른 접근을 시도하고 당신을 위해 무엇이 최선인:되지 않을 수도 있습이 어떤 성능 문제에 모두.