saurabh agarwal
saurabh agarwal

Reputation: 2184

How to sort each character string of character string array

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 ?

Upvotes: 2

Views: 80

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

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

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

Upvotes: 6

Related Questions