Development Tip

C ++ 문자열의 문자 정렬

yourdevel 2020. 11. 7. 10:36
반응형

C ++ 문자열의 문자 정렬


문자열이있는 경우 문자를 정렬하는 기능이 내장되어 있습니까? 아니면 직접 작성해야합니까?

예를 들면 :

string word = "dabc";

다음과 같이 변경하고 싶습니다.

string sortedWord = "abcd";

아마도 char을 사용하는 것이 더 나은 옵션일까요? C ++에서 어떻게할까요?


표준 라이브러리의 헤더에 정렬 알고리즘 이 있습니다 <algorithm>. 제자리에 정렬되므로 다음을 수행하면 원래 단어가 정렬됩니다.

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

원본을 잃어 버리지 않으려면 먼저 사본을 만드십시오.

std::string sortedWord = word;
std::sort(sortedWord.begin(), sortedWord.end());

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

여기를 참조 하십시오


C ++ 표준 템플릿 라이브러리 인 헤더 파일에있는 sort함수 를 포함시켜야 합니다 .algorithm

사용법 : 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;
}

산출:

abcd


sort () 함수를 사용할 수 있습니다 . 알고리즘 헤더 파일 에 sort ()가 있습니다.

        #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;
        }

산출:

Achklors

참고 URL : https://stackoverflow.com/questions/9107516/sorting-characters-of-ac-string

반응형