9.5.3节练习

string搜索操作:

//搜索操作返回指定字符出现的下标,如果未找到则返回npos。
s.find(args);  //查找s中args第一次出现的位置
s.rfind(args);  //查找s中args最后一次出现的位置
s.find_first_of(args); //在s中寻找args中任何一个字符最后一次出现的位置。
s.find_last_of(args);  //在s中查找args中任何一个字符最后一次出现的位置。
s.find_first_not_of(args);  //在s中查找第一个不在args中出现的位置。
s.find_last_not_of(args); //在s中寻找最后一个不在args中出现的字符。

练习9.47:编写程序,首先查找string“abc3d7R4E6”中的每个数字字符,然后查找其中每个字母字符。编写两个版本的程序,第一个要使用find_first_of,第二个要使用find_first_not_of. 

用find_first_of的情况

string st = "ab2c3d7R4E6";
string mun = "0123456789";
string alfa = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
string::size_type pos = 0;
while((pos=st.find_first_of(mun, pos)) != string::npos){
    cout<<st[pos]<<endl;
    ++pos;
}

pos = 0;
while((pos=st.find_first_of(alfa, pos)) != string::npos){
    cout<<st[pos]<<endl;
    ++pos;
}

用find_first_not_of的情况。

	string st = "ab2c3d7R4E6";
	string mun = "0123456789";
	string alfa = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	string::size_type pos = 0;
	while ((pos = st.find_first_not_of(alfa, pos)) != string::npos){
		cout << st[pos] << endl;
		++pos;
	}
	pos = 0;
	while ((pos = st.find_first_not_of(mun, pos)) != string::npos){
		cout << st[pos] << endl;
		++pos;
	}

练习9.48:假定name和numbers的定义如325页所示,numbers.find(name)返回什么?

string numbers("0123456789"), name("r2d2");

因为numbers中不存在和name中重合的字符串所以,返回string::npos;

练习9.49:如果一个字母延伸到中线之上,如d或f,则称其有上出头部分(ascender),如果一个字母延伸到中线之下,如p或g,则称其有下出头部分(descender)。编写程序,读入一个单词文件,输出最长的既不包含上出头部分,也不包含下出头部分的单词。 

	string alfa = "acemnorsuvwxyz";
	string input;
	string best_long;
	string curr;
	cin >> input;
	for (string::size_type i = 0; i < input.size(); i++){
		if (alfa.find(input[i]) != string::npos){
			curr = curr + input[i];
		}
		else{
			if (curr.size() > best_long.size())
				best_long = curr;
			curr.erase(0);
		}
	}
	if (curr.size() > best_long.size())
		best_long = curr;
	cout << best_long << endl;

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值