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

How to sort each character string of character string array

本文关键字:字符串 排序 数组      更新时间:2023-10-16

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

#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);在这里是有效的语句,如果没有,该怎么办?

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 ( size_t i = 0; i < sizeof( str ) / sizeof( *str ); i++ ) sort_word( str[i] );