蘭州大學上機題——字符串匹配並刪除子字符串
題目描述:
輸入一個字符串,例如asdfghj,然後又給了一個字符串,sdfg,要求將輸入字符串中的sdfg刪除,就是相當於刪除子字符串。
算法思路:
先找到子字符串的位置,再進行刪除操作,字符串匹配這裏用BF算法解決。刪除操作這裏是先把子字符串後面的元素往前移動替換子字符串的元素,然後刪除剩下多餘的元素。
#include<iostream>
#include<string>
using namespace std;
//暴力法解決字符串匹配
int BF(string str1, string str2) {
int len1 = str1.length();
int len2 = str2.length();
//如果子字符串的長度大於字符串長度,一定不匹配
if (len1 < len2)
return -1;
int i = 0, j = 0;
while (i < len1 && j < len2) {
if (str1[i] == str2[j]) {
i++;
j++;
}
else {
i = i - j + 1;
j = 0;
}
}
if (j >= len2) {
return i - len2;
}
else
return -1;
}
//刪除子字符串
void delet(string str1, string str2) {
int start = BF(str1, str2);
//如果字符串不匹配直接跳出
if (start < 0) {
cout << "字符串不匹配" << endl;
return;
}
int len1 = str1.length();
int len2 = str2.length();
//令兩個索引,一個指向要刪除的元素,一個指向要往前移動的元素
int i = start, j = start + len2;
//把刪除位置後面的元素往前移動
while (j < len1) {
str1[i] = str1[j];
i++;
j++;
}
//把後面多餘的元素刪除
while (i < len1) {
str1[i] = '\0';
i++;
}
cout << str1;
}
int main() {
string str1, str2;
cout << "輸入主字符串:";
cin >> str1;
cout << "輸入子字符串:";
cin >> str2;
delet(str1, str2);
return 0;
}
運行測試結果: