Given an array of pointers to ordinary C NUL-terminated (and typically very long) strings, how can we best find the smallest and the largest strings?
views:
215answers:
6Maybe for looping through them will help? - Ok, you don't want C++ idea, let's see:
Ok, again:
char **strings; // initialized
int stringsNumber = 500; // number of string in first dimension
int longestLen = 0;
int shortestLen = MAX_INT; // or other REALLY BIG number ;]
char *longest = NULL;
char *shortest = NULL;
int current = 0;
for(int i =0; i < stringsNumber; i++)
{
current = strlen(strings[i]);
if(current > longestLen) { longestLen = current; longest = strings[i]; }
if(current < shortestLen) { shortestLen = current; shortest = strings[i]; }
}
You can have another array of char pointers of size n, with its ith pointer pointing to the start of the ith string.
Increment each pointer till it reaches the end.
The first one to reach the end was the pointer to the shortest string.
The last one to reach the end was the pointer to the longest string.
If it's given to you and you don't manage it - iteration over array and strlen
.
If you manage it - consider using std::string
or pair<char *, int>
(string,length) to optimize your code as well as replacing array of pointers with some ordered container.
I repeat my question.
What do you mean array of pointer to strings
?
Do you mean what you say?
typedef char *string; /* excuse the reserved identifier */
typedef string *pointer_to_string;
pointer_to_string ARRAY_OF_POINTER_TO_STRING[3];
string *ss = malloc(3 * sizeof *ss);
ss[0] = "one"; ss[1] = "two"; ss[2] = "three";
ARRAY_OF_POINTER_TO_STRING[0] = ss;
/* first attempt at demonstrating `array of pointer to string` was invalid *
ARRAY_OF_POINTER_TO_STRING[1] = {"um", "dois", "tres"};
ARRAY_OF_POINTER_TO_STRING[2] = {"un", "deux", "trois"};
*/
free(ss);
Or simply array of char *
?
typedef char *string; /* excuse the reserved identifier */
string ARRAY_OF_CHAR_STAR[3];
ARRAY_OF_CHAR_STAR[0] = "one";
ARRAY_OF_CHAR_STAR[1] = "two";
ARRAY_OF_CHAR_STAR[2] = "three";
If the strings are really really long, you should consider saving them with a length attribute, which is computed already during entering the strings.