Skip to content

Instantly share code, notes, and snippets.

@kkdai
Last active January 4, 2016 14:19
Show Gist options
  • Save kkdai/8633977 to your computer and use it in GitHub Desktop.
Save kkdai/8633977 to your computer and use it in GitHub Desktop.
Print Nst Long string of a series of string.
void PrintLongN(int N, const char *str)
{
//error check
if (N <=0 || *str == NULL)
{
assert(0);
printf("error! \n");
return;
}
//Initial string array
char paseStr[256];
strcpy (paseStr, str);
char *Parse_arrys[256] = {0};
char *token;
char *search = " ";
//Parse all string
int strArray_counter=0;
for(token = strtok(paseStr, search) ; token ; token = strtok(NULL, search))
{
Parse_arrys[strArray_counter] = token;
strArray_counter++;// index counting.
}
//quick sort
char* tmpStr;
for (int i = 0; i < strArray_counter; i++)
{
for (int j = strArray_counter - 1; j > i; j--)
{
if (strlen(Parse_arrys[j]) > strlen(Parse_arrys[j-1]))
{
tmpStr = Parse_arrys[j-1];
Parse_arrys[j-1] = Parse_arrys[j];
Parse_arrys[j] = tmpStr;
}
}
}
for(int i=0; i< N; i++)
printf("[%d]Nst string =%s, size=%d \n", i+1, Parse_arrys[i], strlen(Parse_arrys[i]));
}
@kkdai
Copy link
Author

kkdai commented Jan 26, 2014

假設有一個function "PrintLongN"宣告為void PrintLongN(int N, const char *str)
假設input string為"a bc def xxxx YYZZZ"
PrintLongN要印出長度為前N名的字串
以上為例, 假設N=2, 要印出xxxx and YYZZZ

Function裡的程式碼要分三段:

if (0<=N) { assert (0); printf("error message"); return; }
先把string chunks 都撈出來
如果string chunks 數目小於等於N,就全部印出來,然後return。 如果string chunks 數目大於N,就挑出最長的N個字串來print

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment