在c++中,从字符串中删除空格的首选方法是什么?我可以循环遍历所有字符,并建立一个新的字符串,但有更好的方法吗?
当前回答
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, " ", "+");
其他回答
# include <算法> 使用命名空间std; Int main() { . . s.erase(删除(s.begin (), s.end (), ' ' ), s.end ()); . . }
来源:
参考资料来自本论坛。
最好的方法是使用算法remove_if和isspace:
remove_if(str.begin(), str.end(), isspace);
现在算法本身不能改变容器(只能修改值),所以它实际上会打乱值,并返回一个指针,指向现在应该结束的位置。所以我们必须调用string::erase来修改容器的长度:
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;
}
我使用下面的工作周围很长时间-不确定它的复杂性。
s.erase (std::独特(s.begin (), s.end(),[](字符,字符f){返回(f = = ' ' | | ==' ');}), s.end ());
当你想删除字符' '和一些例如-使用
s . wipe (std:: unique (s .(初),s . end (), [] (char s, char (f) {return ((f = = ' | | s = = ' ') | | (f = = ' - ' | | s =='-'));}), s end ());
同样,如果你想删除的字符数量不是1,只需要增加||
但是正如其他人所提到的,“删除”这个习语似乎也不错。
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, " ", "+");
我创建了一个函数,从字符串的两端移除空白。如 “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;
}
推荐文章
- 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'关键字?
- 如何删除字符串的第一个和最后一个字符