简体   繁体   中英

Separating and lexically ordering strings

I'm supposed to create a function that will print each word from a string to a new line, but it's also supposed to be sorted in lexicographically and that is where I'm stumped. I know how to sort lexicographically if each word were inputted manually by the user ( scanf() ), but if I am using my own string sentence, I'm lost on how to start this. I know I'm supposed to use strcmp() when it comes to comparing strings, but how do I compare each word when the string is "layed out like this"?

This is what I have so far:

#include <stdio.h>
#include <string.h>

void ParseSentence ( char string[] );

int main()
{
    char s[100];

    strcpy ( s , "hello world, how are you today.");

    printf("%s\n", s);

    ParseSentence ( s );
}

/*Objective: Isolates the words in a string, printing them on separate lines 
and omitting any deliminators*/
/*Input: A string of choice is passed as a character array*/
/*Output: void*/ 
void ParseSentence( char string[])
{
    char *tokenPtr, *DelimList = ", ;.";

    tokenPtr = strtok(string, DelimList);

    while (tokenPtr != NULL)
    {
        printf("%s \n", tokenPtr);
        tokenPtr = strtok(NULL, DelimList);
    }

    return;
}

Make an array of "strings" (that is, pointers to char arrays) and sort the array with qsort . Then you can print it in order.

You can populate your aray with the pointers returned from strtok ; there's no need to copy the words. But please note that strtok will destroy the string passed as an argument, so it might have been a good idea to have copied that string before unleashing strtok on it. That would let you define your function to take a const char* argument, allowing you to call it with a string literal. In general, it's better interface design to always use const char* as the prototype for a function taking a string(unless the purpose of the function is to modify the string.)

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