关于c++ [ ]符号的编写 急~~~

[复制链接]
查看11 | 回复3 | 2009-11-17 10:27:36 | 显示全部楼层 |阅读模式
重载[]
回复

使用道具 举报

千问 | 2009-11-17 10:27:36 | 显示全部楼层
重载[](因为string的下标操作符不会这样操作的,对吧)重载以后,函数内部可以调用string的库函数。string自带了一些函数,本例中正需要find查找函数。(一定看一下这个函数msdn)找到"[ "找到"]" ,由于查找函数find返回的在字符串中的下标位置,刚好其差值(就是[]之间的字符数)可以用来new新的sting对象保存。然后增加其实查找起始位置pos 可以遍历整个字符串只要能把[]中的对象找出来输出 不是困难的事情 用string的下标操作符[]或者at()都可以正常输出。这是我的一点想法,希望对你有帮助。
回复

使用道具 举报

千问 | 2009-11-17 10:27:36 | 显示全部楼层
模式匹配都可以用正则,C++的正则库可以用boost
回复

使用道具 举报

千问 | 2009-11-17 10:27:36 | 显示全部楼层
// 1,2楼先看清楚问题。// sascsy是对的。// 不过我想LZ这个“题目”应该是要求不使用正则表达式库来完成这个简单的匹配。#include #include #include using namespace std;void print_all_matching_strings_with_prefix(const string& prefix,
const string& pattern) { size_t open_bracket_index = pattern.find('['); if (open_bracket_index == string::npos) {cout << prefix << pattern << "\n";return; }size_t close_bracket_index = pattern.find(']'); if (close_bracket_index == string::npos) {throw runtime_error("error: bad pattern, can't find matching right bracket."); } string new_prefix = prefix + pattern.substr(0, open_bracket_index); string new_pattern = pattern.substr(close_bracket_index + 1); for (int i = open_bracket_index + 1; i < close_bracket_index; i++) {print_all_matching_strings_with_prefix(new_prefix + pattern,
new_pattern); }}/** * @brief print all strings that matches given pattern. * pattern can contain chars and a special structure []. * [] means fetch any char from the containing list. */void print_all_matching_strings(const string& pattern) { print_all_matching_strings_with_prefix("", pattern);}int main(){ print_all_matching_strings("ab[12]cd[34]ef"); cout << "\n"; print_all_matching_strings("a[021]b[12]cd[34]ef");return 0;}// output:// ab1cd3ef// ab1cd4ef// ab2cd3ef// ab2cd4ef// a0b1cd3ef// a0b1cd4ef// a0b2cd3ef// a0b2cd4ef// a2b1cd3ef// a2b1cd4ef// a2b2cd3ef// a2b2cd4ef// a1b1cd3ef// a1b1cd4ef// a1b2cd3ef// a1b2cd4ef
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行