Is it possible to use std::sort
defined inside <algorithm>
for sorting char
arrays according to their ASCII value? If yes, please provide an example.
The main logic is to toCharArray() method of the String class over the input string to create a character array for the input string. Now use Arrays. sort(char c[]) method to sort character array. Use the String class constructor to create a sorted string from a char array.
Yes. That is definitely possible. You could know that just by writing some sample code, such as this: char charArray[] = {'A','Z', 'K', 'L' }; size_t arraySize = sizeof(charArray)/sizeof(*charArray); std::sort(charArray, charArray+arraySize); //print charArray : it will print all chars in ascending order.
C library function - qsort() The C library function void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*)) sorts an array.
Yes. That is definitely possible. You could know that just by writing some sample code, such as this:
char charArray[] = {'A','Z', 'K', 'L' };
size_t arraySize = sizeof(charArray)/sizeof(*charArray);
std::sort(charArray, charArray+arraySize);
//print charArray : it will print all chars in ascending order.
By the way, you should avoid using c-style arrays, and should prefer using std::array
or std::vector
.
std::array
is used when you know the size at compile-time itself, while std::vector
is used when you need dynamic array whose size will be known at runtime.
Yes:
char array[] = "zabgqkzg";
std::sort(array, array+sizeof(array));
See http://ideone.com/0TkfDn for a working demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With