[Accelerated c++读书笔记] 读入一行,拆分每个word。

很多C++书籍都鼓励我们使用vector替换数组,使用string替换传统的字符串,我一直相信可以这么做,而且这么做了以后,会减少工作量,提高效率。知道是一回事,实际操作起来是一回事,每次使用string的时候总会有这样那样的问题。我在想,之所以Accelerated c++这本书这么有名,或许就是因为作者直接教我们用C++的方式思考,这本书只看了一小部分,但是有个例子很能说明问题——作者教我们如何以C++的方式思考。


下面的两个程序都是实现相同的功能,读入一行,如后将该句子里的单词拆分出来。

程序1:

#include<iostream> #include<vector> #include<cctype> #include<string> using namespace std; vector<string>split(const string&s) { vector<string> ret; typedef string::size_type string_size; string_size i = 0; while( i != s.size() ) { while( i != s.size() && isspace(s[i])) ++i; string_size j =i; while( j != s.size() && ! isspace( s[j])) ++j; if( i != j) { ret.push_back( s.substr(i,j - 1 )); i = j; } } return ret; } int main() { string str; getline( cin, str); vector<string> vec = split( str ); cout << " vec.size() = " << vec.size() << endl; cout << str << endl; return 0; }

程序2(纯C++实现):

#include<iostream> #include<vector> #include<cctype> #include<string> #include<algorithm> using namespace std; bool space( char c) { return isspace(c); } bool not_space( char c) { return !isspace(c); } vector<string> split( const string& str) { typedef string::const_iterator iter; vector<string> ret; iter i = str.begin(); while( i != str.end()) { i = find_if( i , str.end(), not_space); iter j = find_if( i, str.end(), space); if ( i != str.end() ) ret.push_back( string( i,j )); i = j; } return ret; } int main() { string str; getline( cin, str); vector<string> vec = split( str ); cout << "vec.size() = " << vec.size() << endl; cout << str << endl; return 0; }



书上还有一个例子很好,可以用来考察一个是否很熟悉STL,用一行代码来判断一个字符串是不是回文:

#include<iostream> #include<algorithm> #include<string> using namespace std; int main() { string str; cin >> str; //核心代码就这么一行 if( equal( str.begin(), str.end(), str.rbegin()) ) { cout << str << " is a plaindrome " << endl; } else { cout << str << " is not a plaindrome " << endl; } return 0; }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值