Friday, March 9, 2012

Sort words by alphabet С++

Hi, this time I'll show you how to  sort words by alphabet on С++.
It's rather easy. 

So here is the code:


#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector> 
#include <algorithm> 


using namespace std; 


string initial = "qwerty asdfgh zxcvbn";
vector<string> s; 


vector<string> split(const string &s, const char *by = " "
{
   vector<string> res;
   int i, j;
   int n = s.size();
   for (i = 0; i <= n; i = j + 1)
    {
      for (j = i; j < n && strchr(by, s[j]) == NULL;) j++;
      res.push_back(s.substr(i, j-i));   
    }


     return res;
}


int _tmain(int argc, _TCHAR* argv[])
{
    cout << "Initial string: " << initial << endl;


    s = split(initial);
    sort(s.begin(),s.end());
    initial = "";


    for (int i=0; i<s.size(); i++)
    {
         initial += s[i]+" ";
    }


     cout << "Final string: " << initial << endl;
   return 0;


 }

No comments:

Post a Comment