01/10/2018, 15:38

Thắc mắc kiểu dữ liệu string

Em muốn thực hiện 1 chuơng trình xóa các ký tự cách khoảng trong chuỗi.

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

int main()
{
	string expression = " a bd e";
	int i = 0;
	while(expression[i] != '' )
	{
		while(expression[i] == ' ') expression.erase(expression.begin()+i);
		i++;
	}
	cout << expression;
	return 0;
}

Đoạn code trên thì thành công.
Nhưng khi em dùng for thì bị lỗi

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

int main()
{
	string expression = " a bd e";
	for (string::iterator ite = expression.begin(); ite != expression.end(); ++ite)
	{
		while(*ite = ' ') expression.erase(ite);
	}
	cout << expression;
	return 0;
}

Mong các bác giải thích giúp em ạ.
Em cám ơn nhiều ạ.

rogp10 viết 17:47 ngày 01/10/2018

Bạn lặp bằng iterator thì bạn phải tiếp nhận iter trả về của phương thức erase.

Bài liên quan
0