Sorting Characters Of A C++ String

前端 未结 4 1102
说谎
说谎 2020-12-22 23:19

If i have a string is there a built in function to sort the characters or would I have to write my own?

for example:

string word = \"dabc\";
<         


        
相关标签:
4条回答
  • 2020-12-22 23:56

    You can use sort() function. sort() exists in algorithm header file

            #include<bits/stdc++.h>
            using namespace std;
    
    
            int main()
            {
                ios::sync_with_stdio(false);
                string str = "sharlock";
    
                sort(str.begin(), str.end());
                cout<<str<<endl;
    
                return 0;
            }
    

    Output:

    achklors

    0 讨论(0)
  • 2020-12-22 23:57

    You have to include sort function which is in algorithm header file which is a standard template library in c++.

    Usage: std::sort(str.begin(), str.end());

    #include <iostream>
    #include <algorithm>  // this header is required for std::sort to work
    int main()
    {
        std::string s = "dacb";
        std::sort(s.begin(), s.end());
        std::cout << s << std::endl;
    
        return 0;
    }
    

    OUTPUT:

    abcd

    0 讨论(0)
  • 2020-12-23 00:12

    There is a sorting algorithm in the standard library, in the header <algorithm>. It sorts inplace, so if you do the following, your original word will become sorted.

    std::sort(word.begin(), word.end());
    

    If you don't want to lose the original, make a copy first.

    std::string sortedWord = word;
    std::sort(sortedWord.begin(), sortedWord.end());
    
    0 讨论(0)
  • 2020-12-23 00:13
    std::sort(str.begin(), str.end());
    

    See here

    0 讨论(0)
提交回复
热议问题