[英]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. 如果用户手动输入了每个单词(
scanf()
),我知道如何按字典顺序进行排序,但是如果我使用自己的字符串语句,那么我将不知道如何开始该单词。 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"? 我知道在比较字符串时应该使用
strcmp()
,但是当字符串“像这样布局”时如何比较每个单词?
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
. 创建一个“字符串”数组(即,指向char数组的指针),然后使用
qsort
对数组进行排序。 Then you can print it in order. 然后您可以按顺序打印它。
You can populate your aray with the pointers returned from strtok
; 您可以使用
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. 但是请注意,
strtok
将破坏作为参数传递的字符串,因此在释放strtok
之前复制该字符串可能是一个好主意。 That would let you define your function to take a const char*
argument, allowing you to call it with a string literal. 这样一来,您就可以定义函数以使用
const char*
参数,并允许您使用字符串文字对其进行调用。 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.) 通常,更好的接口设计是始终使用
const char*
作为采用字符串的函数的原型(除非该函数的目的是修改字符串)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.