如何对字符串数组的每个字符串进行排序

时间:2016-06-22 13:40:05

标签: c++ string sorting

我想对每个字符串数组进行排序,这是我尝试过的代码。

#include <iostream>
#include <algorithm>

void _sort_word(char *str)
{
    int len = strlen(str); 
    std::sort(str,str+len); // program get stuck here. 
}
int main()
{
    char *str[] = {"hello", "world"};
    for(int i=0;i<2;i++){
        _sort_word(str[i]);
        cout << str[i] << "\n";
    }
}

我想知道sort(str,str+len);这里有一个有效的陈述,如果不是应该做什么呢?

1 个答案:

答案 0 :(得分:6)

首先,C ++中的字符串文字具有常量字符数组的类型。所以正确的数组声明看起来像

const char *str[] = {"hello", "world"};
^^^^^

因此,数组元素指向的字符串文字是不可变的。

您应该至少声明一个二维数组。

这是一个示范程序

#include <iostream>
#include <algorithm>
#include <cstring>

void sort_word( char *s )
{
    size_t l = std::strlen( s ); 
    std::sort( s, s + l ); 
}


int main() 
{
    char str[][6] = { "hello", "world" };

    for ( auto &s : str ) sort_word( s );
    for ( auto &s : str ) std::cout << s << std::endl;

    return 0;
}

它的输出是

ehllo
dlorw

如果您的编译器不支持基于for语句的范围,那么您可以改为编写

for ( size_t i = 0; i < sizeof( str ) / sizeof( *str ); i++ ) sort_word( str[i] );
相关问题