惨痛教训:string > < 比较的仅仅是头一个字母!!!!

 

代码
1 #include <iostream>
2 #include <string>
3  using namespace std;
4  int HowManyWord(string sentence)
5 {
6 int words=1;
7 for(string::size_type i=0;i!=sentence.size();++i)
8 if(sentence[i]==' ')
9 ++words;
10 return words;
11 }
12 string LongestWord(string sentence)
13 {
14 string back,longest;
15 for(string::size_type i=0;i!=sentence.size();++i)
16 if(sentence[i]==' ')
17 {
18 if(back>longest)\\key problem
19 \\应该改为back.size()>longest.size()先比第一个字母字母相同让后第二个。。。
20
21 longest=back;
22 back="";
23 }
24 else
25 back+=sentence[i];
26 return longest;
27 }
28 string ShortestWord(string sentence)
29 {
30 string back,shortest="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
31 for(string::size_type i=0;i!=sentence.size();++i)
32 if(sentence[i]==' ')
33 {
34 if(back<shortest)
35 shortest=back;
36 back="";
37 }
38 else
39 back+=sentence[i];
40 return shortest;
41 }
42 int main()
43 {
44 string line1="We were her pride of 10 she named us:";
45 string line2="Benjamin, Phoenix, the Prodigal";
46 string line3="and perspicacious pacific Suzanne";
47 string sentence=line1+' '+line2+' '+line3;
48 cout<<"There are " <<HowManyWord(sentence) <<" words." <<endl;
49 cout<<"LongestWord:" <<LongestWord(sentence) <<endl;
50 cout<<"ShortestWord:" <<ShortestWord(sentence) <<endl;
51 return 0;
52 }

 

posted on 2010-11-03 22:50  decem  阅读(155)  评论(0)    收藏  举报

导航