首页 > 代码库 > 删除String中的空格

删除String中的空格

三种删除String中空格的方法。可用根据需要自由进行选择使用。

1、C风格

#include "stdafx.h"void RemoveStringSpaces(char* pStr);int _tmain(int argc, _TCHAR* argv[]){    return 0;}void RemoveStringSpaces(char* pStr){    int i = 0;                             // ‘Copy to‘ index to string    int j = 0;                             // ‘Copy from‘ index to string    while ((*(pStr + i) = *(pStr + j++)) != \0)  // Loop while character        // copied is not \0        if (*(pStr + i) !=  )                    // Increment i as long as            i++;                                  // character is not a space    return;}

 

2、STL 算法

  remove与remove_if

#include "stdafx.h"#include <algorithm>#include <functional>#include <string>using namespace std;void RemoveStringSpaces(string& str);int _tmain(int argc, _TCHAR* argv[]){    return 0;}void RemoveStringSpaces(string& str){    str.erase(remove(str.begin(), str.end(),  ), str.end());    //str.erase(remove_if(str.begin(), str.end(), bind2nd(equal_to<char>(), ‘ ‘)), str.end()); 效果与remove一样}

 

3、ctype

#include "stdafx.h"#include <string>#include <cctype>using namespace std;void RemoveStringSpaces(string& str);int _tmain(int argc, _TCHAR* argv[]){    return 0;}void RemoveStringSpaces(string& str){    for (size_t index = 0; index != str.size();)    {        if (isspace(str[index])) //如果str[index]为空白,则为Ture            str.erase(index, 1);        else            ++index;    }}

 

PS:使用过程中注意添加正确的头文件。

删除String中的空格