Compare length of two strings: Difference between revisions

No edit summary
Line 39:
=={{header|C}}==
{{Works with|C11}}
<lang C>#include <stdio.h>
#include <stdlib.h>
</lang>
#include <string.h>
 
 
void cmp(int* a, int* b)
{
return *b - *a; // reverse sort!
}
 
void compareAndReportStringsLength(char* strings[], int n)
{
if (n > 0)
{
const char* has_length = "has length";
const char* predicate_max = "and is the longest string";
const char* predicate_min = "and is the shortest string";
const char* predicate_ave = "and is neither the longest nor the shortest string";
 
int* si = malloc(2 * n * sizeof(int));
if (si != NULL)
{
for (int i = 0; i < n; i++)
{
si[2 * i] = strlen(strings[i]);
si[2 * i + 1] = i;
}
qsort(si, n, 2 * sizeof(int), cmp);
 
int max = si[0];
int min = si[2 * (n - 1)];
 
for (int i = 0; i < n; i++)
{
int length = si[2 * i];
char* string = strings[si[2 * i + 1]];
char* predicate;
if (length == max)
predicate = predicate_max;
else if (length == min)
predicate = predicate_min;
else
predicate = predicate_ave;
printf("\"%s\" %s %d %s\n",
string, has_length, length, predicate);
}
 
free(si);
}
else
{
fprintf(stderr, "unable allocate memory buffer");
}
}
}
 
int main(int argc, char* argv[])
{
char* list[] = {"abcd", "123456789", "abcdef", "1234567"};
 
compareAndReportStringsLength(list, 4);
 
return EXIT_SUCCESS;
}</lang>
{{output}}
<pre></pre>
"123456789" has length 9 and is the longest string
"1234567" has length 7 and is neither the longest nor the shortest string
"abcdef" has length 6 and is neither the longest nor the shortest string
"abcd" has length 4 and is the shortest string
</pre>
 
=={{header|FreeBASIC}}==