輸入兩個字符串,從第一字符串中刪除第二個字符串中所有的字符。 例如,輸入”They are students.”和”aeiou”,則刪除之後的第一個字符串變成”Thy r stdnts.”

1.題目

輸入兩個字符串,從第一字符串中刪除第二個字符串中所有的字符。
例如,輸入”They are students.”和”aeiou”,則刪除之後的第一個字符串變成”Thy r stdnts.”
輸入描述 :
每個測試輸入包含2個字符串
輸出描述 :
輸出刪除後的字符串
示例1
輸入
複製
They are students.
aeiou
輸出
複製
Thy r stdnts.

2 .代碼展示

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<string>
using namespace std;
int main()
{
	string s1, s2;
	getline(cin, s1);
	getline(cin, s2);
	auto it1 = s1.begin();
	auto it2 = s2.begin();
	while (it1 != s1.end())
	{
		auto begin = it2;
		while (begin != s2.end())
		{
			if (*begin == *it1)
			{
				it1 = s1.erase(it1);
				--it1;//由於erase函數的返回值是下一個位置
			}
			else
			{
				++begin;
			}
		}
		++it1;
	}
	cout << s1 << endl;
	system("pause");
	return 0;
}
/*
	string s1,s2, s;
	getline(cin, s1);
	getline(cin, s2);
	auto it1 = s1.begin();
	auto it2 = s2.begin();
	while (it1 != s1.end())
	{
		int flag = 0;
		auto begin = it2;
		while (begin != s2.end())
		{
			if (*begin == *it1)
			{
				flag = 1;
                break;
			}
				++begin;
		}
		if (flag == 0)
		{
			s += *it1;
		}
		++it1;
	}
	cout << s << endl;
*/

3.解題思路

首先我們將s1中的每一位和s2中的每一位都進行比較,將相同的刪除,如果用erase的話,要注意刪除是移動後面的數據到當前位置,所以有可能造成當前數據沒有和s2之前的數據進行比較,所以要將當前的位置-1,另外就是erase每次刪除都要移動,所以爲了避免這種不必要的事件浪費,所以我們新創建一個對象,將不同的儲存起來就好。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章