c++字符串排序
场景:关于C++字符串排序解决方法
关于C++字符串排序
为了让大家看的速度而且明白。我专门写了一个很简单的程序来说明问题。
#include<string>
#include<iostream>
using namespace std;
void main()
{
string name="what's up dude";
int i = 0;
while(name[i]!='\0')
{
cout<<name[i];
if(name[i++]==' ')
{
cout<<endl;
}
}
}
这个程序是输出这个字符串,并且一行显示一个单词。如果直接cout<<name;就会显示在一行。
我想问的问题是如何给字符串name里面的单词按照单词长短排序(从小到大);输出结果为
up
dude
what's
请问各路高手有没有简单的方法实现这个功能。希望对一大段文字同样适用的程序。谢谢
------解决方案--------------------
关于C++字符串排序
为了让大家看的速度而且明白。我专门写了一个很简单的程序来说明问题。
#include<string>
#include<iostream>
using namespace std;
void main()
{
string name="what's up dude";
int i = 0;
while(name[i]!='\0')
{
cout<<name[i];
if(name[i++]==' ')
{
cout<<endl;
}
}
}
这个程序是输出这个字符串,并且一行显示一个单词。如果直接cout<<name;就会显示在一行。
我想问的问题是如何给字符串name里面的单词按照单词长短排序(从小到大);输出结果为
up
dude
what's
请问各路高手有没有简单的方法实现这个功能。希望对一大段文字同样适用的程序。谢谢
------解决方案--------------------
- C/C++ code
#include<string> #include<iostream> #include<sstream> #include<vector> #include<algorithm> using namespace std; bool cmp(string& a, string& b) { if(a.size() < b.size()) { return true; } else { return false; } } void main() { string name="what's up dude"; istringstream stream(name); string word; vector<string> vc; while(stream>>word) { vc.push_back(word); } sort(vc.begin(), vc.end(), cmp); for(int i = 0; i < vc.size(); ++i) { cout<<vc[i]<<endl; } }