简体   繁体   中英

How to shuffle characters within a string in C

I am creating a program and part of it needs to take a word, and jumble the letters. I know that there is officially no string data type within C, so technically the characters in the word are already in array? They just need sorting. (That is my understanding anyway). I also know that C isn't very good for actual random numbers, I normally use the time as the seed, not sure if this would affect shuffling the letters.

For instance:

The word Hello
Split into Characters H/E/L/L/O
Shuffled E/L/O/H/L
New word Elohl

technically the characters in the word are already in array?

You can treat them like a null-terminated array of characters. Apply your favorite shuffle algorithm to the portion of the string between 0, inclusive, and strlen(str) , exclusive to produce a shuffled string.

The only catch here is that not all strings can be shuffled in place. Specifically, strings representing string literals are not writable. Trying to change them would lead to undefined behavior.

For example, if you do

char *word = "hello";
shuffle(word);

and try to modify word 's characters inside shuffle , you would get undefined behavior. You need to copy the content into a writable array before you can shuffle the content - for example, like this:

char word[] = "hello";
shuffle(word);
int compare(const void *a, const void *b){
        return *(const char *)a - *(const char *)b;
    }

    char arr[] = "dbaurjvgeofx";

    printf("Unsorted: %s\n", arr);
    qsort(arr, strlen(arr), 1, compare);
    printf("Sorted: %s\n", arr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM