字符串排序,c++实现
字符串排序
http://www.nowcoder.com/questionTerminal/5190a1db6f4f4ddb92fd9c365c944584
基于冒泡排序
#include <iostream> #include <string> #include <vector> using namespace std; void sort(vector<char>& ch);//.adb.A int main() { string words; string out; vector<char> ch; while (getline(cin, words)) { out.clear(); ch.clear(); for (auto& i : words) {//将所有字母存入容器中 if (isalpha(i)) {//判断是否为字母 ch.push_back(i); } } sort(ch); for (int i = 0, j = 0; i < static_cast<int>(words.size()); i++) { if (isalpha(words[i])) { out += ch[j++];//字母 } else { out += words[i];//非字母 } } cout << out << endl; } } void sort(vector<char>& ch)//A Famous Saying: M { int len = static_cast<int>(ch.size()); for (int i = 0; i < len - 1; i++) { for (int j = 0; j < len - i - 1; j++) { if (tolower(ch[j]) > tolower(ch[j + 1])) { char temp = ch[j]; ch[j] = ch[j + 1]; ch[j + 1] = temp; } } } }