2015-09-04 47 views
-7

我用“using namespace std”在我的整个C++研究中,基本上我不明白std :: out之类的东西,请帮我解决。比方说,我有一个如下所示的代码,我希望两个字符串在我比较时是相同的。如何从C++中的字符串中删除空格

int main(void) 
{ 
    using namespace std; 
    char a[10] = "123 "; 
    char b[10] = "123"; 
    if(strcmp(a,b)==0) 
    {cout << "same";} 
return 0; 
} 
+0

检查这个线程:) http://stackoverflow.com/questions/使用功能5891610/how-to-string-characters-from-a-string – Zerray

+1

'std :: cout'真的很可怕吗?这只是另一个完全相同的名字。 – john

+1

你的问题是不明确的,你想从字符串中删除所有空格,你只是想从字符串的末尾删除它们,也许你想从开始和结束,但不是中间删除它们?您需要清楚地询问您是否需要适当的答案。 – john

回答

0

使用正则表达式\\s+匹配所有空格字符,并使用regex_replace删除它

#include <iostream> 
#include <regex> 
#include <string> 

int main() 
{ 
    std::string text = "Quick brown fox"; 
    std::regex spaces("\\s+"); 

    // construct a string holding the results 
    std::string result = std::regex_replace(text, spaces, ""); 
    std::cout << '\n' << text << '\n'; 
    std::cout << '\n' << result << '\n'; 
} 

参考http://en.cppreference.com/w/cpp/regex/regex_replace

+0

一个例子会很好。 – Wtower

0

如果您使用的std :: string代替字符,你可以使用来自boost的截断函数。

0

使用std::string

std::string a("123  "); 
std::string b("123"); 
a.erase(std::remove_if(a.begin(), a.end(), ::isspace), a.end()); 
if (a == b) 
    std::cout << "Same"; 

通过using带来的变化将是

using namespace std; 
string a("123  "); 
string b("123"); 
a.erase(remove_if(a.begin(), a.end(), ::isspace), a.end()); 
if (a == b) 
    cout << "Same"; 

通常建议不要使用using namespace std。不要忘记包括<string><algorithm>

编辑如果您仍然想这样做的C方式,从这个帖子

https://stackoverflow.com/a/1726321/2425366

void RemoveSpaces(char * source) { 
    char * i = source, * j = source; 
    while (*j != 0) { 
     *i = *j++; 
     if (*i != ' ') i++; 
    } 
    *i = 0; 
}