sorting a single string that is separted by spaces

given string is
abc abaa banana ban caba
answer should be
abc ab ban ban cab
i need to sort and delete the duplicates in the string.how can i approach the problem in c++

There are two cases:

Case 1:
we know the number of space-separated strings.

for this

vector<string> v;
string a;
for(int i = 0; i < n; ++i){
  cin >> a;
  v.push_back(a);
}

Case 2: We don’t know n

vector<string> v;
string a,b;
getline(cin,a);
istringstream ss(a);
while(getline(ss,b,' ')){
   v.push_back(b);
}

Now All we have to do is sort the vector

Use:

sort(v.begin(),v.end());

Advice: if you don’t know sorting algorithms, learn them thoroughly. You will need them. Do not be dependent on sort.

1 Like