C ++ 문자열의 문자 정렬


82

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

예를 들면 :

string word = "dabc";

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

string sortedWord = "abcd";

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


7
어때 std::sort?
dreamlax

모든 종류의 순진한 char 값 기반 정렬은 UTF-8로 중단됩니다-문자열에 따라 로케일을 고려할 수 있습니다.
Christian Severin

답변:


146

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

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

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

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

문자열을 오름차순으로 정렬하려면 어떻게해야합니까?
The Room

3
@madhuspot std::sort은 기본적으로 알파벳 내림차순으로 정렬합니다. 그 치죠하는 것은 사소한 오타 그리고 당신이 원하는 의 버전 사용 순서를 구김 std::sort이가 소요 Compare세 번째 인수로하고 공급하는 std::greater대신 기본으로 std::less. 기본적으로 유형을 std::string사용 char하므로 예를 들어 std::sort(sortedWord.begin(), sortedWord.end(), std::greater<char>());— 원래 질문에서 "abcd"가 아닌 "dcba"의 결과를 제공합니다.
Tommy

3
@madhuspot 또는 std :: reverse 사용
Vincent

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

여기를 참조 하십시오


10
이것이 최선의 방법입니다 ... 문자열이 단일 바이트 인코딩을 사용하는 경우. 그렇지 않으면 문자를 구성 요소 바이트로 분리합니다.
Ben Voigt 2012

2

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


1

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

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.