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

时间:2022-11-29 10:46:12

I want to sort each string of array of strings , here is my code that i tried.

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

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

I want to know is sort(str,str+len); a valid statement here, if not what should be done instead ?

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

1 个解决方案

#1


6  

First of all string literals in C++ have types of constant character arrays. So the correct array declaration will look like

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

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

Thus the string literals pointed to by the elements of the array are immutable.

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

You should declare at least a two dimensional array.

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

Here is a demonstrative program

这是一个示范计划

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

Its output is

它的输出是

ehllo
dlorw

If your compiler does not support the range based for statement then you can write instead

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

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

#1


6  

First of all string literals in C++ have types of constant character arrays. So the correct array declaration will look like

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

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

Thus the string literals pointed to by the elements of the array are immutable.

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

You should declare at least a two dimensional array.

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

Here is a demonstrative program

这是一个示范计划

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

Its output is

它的输出是

ehllo
dlorw

If your compiler does not support the range based for statement then you can write instead

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

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