首页 > 代码库 > 删除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中的空格
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。