简体   繁体   English

在字符串C的数组上合并排序

[英]Merge sort on array of string C

Is it possible to merge sort an array of strings? 是否可以合并对字符串数组进行排序? For example if I have an array of strings in C like... 例如,如果我在C中有一个字符串数组,例如...

arr[0]="Hello";
arr[1]="cat";
arr[2]="there";
arr[3]="apple";
arr[4]="flower";

The sorted output should be... 排序后的输出应为...

apple
cat 
flower
hello
there

Also I don't understand what I should do if I have 2 words like "Hello" and "Hell?" 另外,如果我有两个单词,例如“ Hello”和“ Hell?”,我也不明白该怎么办。 Everywhere the examples are always for integers and never strings especially in C++. 例子到处都是整数,而不是字符串,尤其是在C ++中。

Yes, in your comparision, use strcmp for C, and std::string::compare for C++. 是的,在比较中,对于C使用strcmp ,对于C ++使用std::string::compare Both functions will compare the strings, and return an integer with the following meanings... 这两个函数将比较字符串,并返回具有以下含义的整数...

  • < 0 — Either the value of the first character that does not match is lower in the compared string, or all compared characters match but the compared string is shorter. <0 —比较字符串中不匹配的第一个字符的值较低,或者所有比较字符都匹配,但比较字符串较短。

  • = 0 — They compare equal = 0 —他们比较相等

  • > 0 — Either the value of the first character that does not match is greater in the compared string, or all compared characters match but the compared string is longer. > 0-比较的字符串中不匹配的第一个字符的值较大,或者所有比较的字符都匹配,但比较的字符串较长。

This will also take into account "Hello" vs. "Hell" and will will subsequently sort "Hell" before "Hello". 这还将考虑“ Hello”与“ Hell”的关系,随后将在“ Hello”之前对“ Hell”进行排序。

Note: If you find that you are like me, and have a hard time remembering what the result means. 注意:如果您发现自己和我一样,并且很难记住结果的含义。 Simply put the comparison operator (as in the example above) inbetween str1 and str2 . 只需将比较运算符(如上面的示例中)放在str1str2 So, for example, if you called strcmp(str1, str2) and the result was < 0 , then look at it like str1 < str2 . 因此,例如,如果调用strcmp(str1, str2)且结果为<0 ,则将其str1 < str2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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