【C++函数题目】删除字符串中的子串

来源:http://acm.ujn.edu.cn

Description

编写函数,去掉str字符串中出现的substr字符串。要求实参和形参之间按引用传递

str字符串为aaas1kaaas,substr字符串为aaa,则输出结果s1ks。

Input

第一行有一个正整数T,表示测试数据的组数。后跟T组测试数据,每组测试数据占两行,第一行是字符串str,第二行是字符串substr。

Output


对于每组测试数据,输出结果占一行,即去掉substr后的str。

Sample Input

2

aaas1kaaas

aaa

zhangwangli

an

Sample Output

s1ks

zhgwgli

 

题解

 1 #include<string>
 2 #include<iostream>
 3 using namespace std;
 4 void delete_string(string& str,string substr);//删除子串的函数
 5 
 6 int main()
 7 {
 8     int T;
 9     cin >> T ;
10     
11     for( int i=0; i<T; i++ )
12     {
13         string str1,str2;
14         cin >> str1 >> str2 ;
15         delete_string(str1,str2);//调用函数
16         cout << str1 << endl;
17     }
18     return 0;
19 }
20 
21 void delete_string(string &str,string substr)
22 {
23     int pos;
24     int l=substr.length();//计算子串长度,也就是要删除的长度
25     while(1)
26     {
27         pos = str.find(substr) ;//查找子串出现的第一个下标
28         if( pos<0 )  break;//如果找不到,退出循环
29         str.erase(pos,l);//如果找到,删除从这个下标开始的子串长度的字符
30     }
31 }

补充:

27行的查找函数,也可以写c_str()函数

pos = str.find( substr.c_str() )

C++中的这个函数是为了与c语言兼容,c中无string类型,故必须通过string类对象的成员函数c_str()把string对象转换成c中的字符串样式.

c_str是String类中的函数,它返回当前字符串的首字符地址。

posted @ 2022-06-11 19:00  杏花疏影  阅读(784)  评论(0)    收藏  举报