我在 C 中有一個不同字串的陣列,例如:
char *words[8] = {"hi", "cheesecake", "yellow", "happy", "cupcake", "red", "car", "chocolate cake"};
我想使用一個函式來過濾它們,比如char *cakes[3] = filterWords(&words, "*cake*");代表*任何東西。有沒有我可以包含的 Linux 庫來做到這一點?如果沒有,實作這一點的最快方法是什么?(我對如何實作這一點有一些想法,但它可能會非常低效)。
uj5u.com熱心網友回復:
我會為此使用該fnmatch功能。它是 POSIX 函式,因此它在 Linux 下可用并且相對易于使用:https : //man7.org/linux/man-pages/man3/fnmatch.3.html 請注意它處理其他通配符模式,例如?,所以如果您的模式來自外部,那么您可能需要特別處理這些字符。
這是一個示例,您可能需要更多的作業才能獲得所需的確切功能:
#include <fnmatch.h>
#include <stdio.h>
int main() {
char *words[8] = {"hi", "cheesecake", "yellow", "happy", "cupcake", "red", "car", "chocolate cake"};
const char *pattern = "*cake*";
int i;
for(i = 0; i < sizeof(words)/sizeof(words[0]); i ) {
if (fnmatch(pattern, words[i], 0) == 0) {
printf("Match: %s\n", words[i]);
}
}
return 0;
}
uj5u.com熱心網友回復:
您可以使用string.h帶有一些技巧的標題來做到這一點。例如,看看下面的代碼片段。(此解決方案是跨平臺的)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// General Time Complexity: O(n), where `n` is the length of string array, (note, time complexities of `strstr`, `strlen` and `strncpy` aren't counted)
char **filter(const char **data, size_t len_data, const char *key, size_t *len_out)
{
if (!data || !key)
return NULL;
char **val = (char **)calloc(len_data, sizeof(char *));
*len_out = 0;
for (size_t i = 0, j = 0; i < len_data; i )
{
if (strstr(data[i], key) != NULL)
{
size_t len_sub = strlen(data[i]);
val[j] = (char *)calloc(len_sub 1, sizeof(char));
strncpy(val[j], data[i], len_sub);
j ;
*len_out = 1;
}
}
return val;
}
int main(void)
{
char *words[8] = {"hi", "cheesecake", "yellow", "happy", "cupcake", "red", "car", "chocolate cake"};
size_t len_data = 0;
char **data = filter((const char **)words, 8, "cake", &len_data);
for (size_t i = 0; i < len_data; i )
{
printf("%s\n", data[i]);
free(data[i]);
}
free(data);
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/426078.html
上一篇:python中Int陣列 字串陣列的連接(類似于R中的paste())?
下一篇:如何在字串中移動(右)子字串?
