从C中的长字符串数组中有效搜索最短和最长的字符串

Vis*_*ish 1 c string algorithm

给定一个指向普通C NUL终止(通常很长)字符串的指针数组,我们如何才能最好地找到最小和最大的字符串?

Gui*_*ois 9

在数组的每个条目上使用strlen.


Tom*_*zyk 5

也许循环遍历它们会有所帮助?- 好吧,你不想要 C++ 的想法,让我们看看:

好的,再说一遍:

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]; }
}
Run Code Online (Sandbox Code Playgroud)