删除C++ string中的空格

stpeace

         最近要用到, 先来写个程序(注意, 后来网友帮我发现, 如下这个程序有问题):

#include <iostream>
#include <map>
#include <string>
using namespace std;
 
void deleteAllMark(string &s, const string &mark)
{
	unsigned int nSize = mark.size();
	while(1)
	{
		unsigned int pos = s.find(mark);
		if(pos == string::npos)
		{
			return;
		}
 
		s.erase(pos, nSize);
	}
}
 
int main()
{
	string s = " abc  def   ";
	string b = "abcdef";
	deleteAllMark(s, " ");
	cout << ((s==b)? "yes": "no")<< endl;
	return 0;
}

问题在哪里呢? 如上是32位(指编译机)机器, 上述程序是OK的, 但如果是64位(指编译机)机器, 就出现问题了:

terminate called after throwing an instance of ‘std::out_of_range’
what(): basic_string::erase: __pos (which is 4294967295) > this->size() (which is 6)
Aborted

应该用更具有移植性质的size_t, 请用如下正确版本的程序:

#include <iostream>
#include <map>
#include <string>
using namespace std;

void deleteAllMark(string &s, const string &mark)
{
   size_t nSize = mark.size();
   while(1)
   {
   	size_t pos = s.find(mark);    //  尤其是这里
   	if(pos == string::npos)
   	{
   		return;
   	}

   	s.erase(pos, nSize);
   }
}

int main()
{
   string s = " abc  def   ";
   string b = "abcdef";
   deleteAllMark(s, " ");
   cout << ((s==b)? "yes": "no")<< endl;
   return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_36784975/article/details/88379197