在c++中,从字符串中删除空格的首选方法是什么?我可以循环遍历所有字符,并建立一个新的字符串,但有更好的方法吗?
当前回答
string removeSpaces(string word) {
string newWord;
for (int i = 0; i < word.length(); i++) {
if (word[i] != ' ') {
newWord += word[i];
}
}
return newWord;
}
这段代码基本上接受一个字符串并遍历其中的每个字符。然后检查该字符串是否为空白,如果不是,则将该字符添加到新字符串中。
其他回答
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, " ", "+");
删除所有空白字符,如制表符和换行符(c++ 11):
string str = " \n AB cd \t efg\v\n";
str = regex_replace(str,regex("\\s"),"");
我创建了一个函数,从字符串的两端移除空白。如 “Hello World”,将转换为“Hello World”。
这类似于python中经常使用的strip、lstrip和rstrip函数。
string strip(string str) {
while (str[str.length() - 1] == ' ') {
str = str.substr(0, str.length() - 1);
}
while (str[0] == ' ') {
str = str.substr(1, str.length() - 1);
}
return str;
}
string lstrip(string str) {
while (str[0] == ' ') {
str = str.substr(1, str.length() - 1);
}
return str;
}
string rstrip(string str) {
while (str[str.length() - 1] == ' ') {
str = str.substr(0, str.length() - 1);
}
return str;
}
std::string::iterator end_pos = std::remove(str.begin(), str.end(), ' ');
str.erase(end_pos, str.end());
string str = "2C F4 32 3C B9 DE";
str.erase(remove(str.begin(),str.end(),' '),str.end());
cout << str << endl;
输出:2 cf4323cb9de
推荐文章
- cplusplus.com给出的错误、误解或坏建议是什么?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 找出质数最快的算法是什么?
- 我可以将c#字符串值转换为转义字符串文字吗?
- 在c#中解析字符串为日期时间
- 字符串中的单词大写
- c++枚举类可以有方法吗?
- string.ToLower()和string.ToLowerInvariant()
- PHP字符串中的花括号
- 格式化IO函数(*printf / *scanf)中的转换说明符%i和%d之间的区别是什么?
- 将析构函数设为私有有什么用?
- main()中的Return语句vs exit()
- 为什么c#不提供c++风格的'friend'关键字?
- 如何删除字符串的第一个和最后一个字符