在c中拆分字符串

我试图在C中分割一个字符串(不是在C#,C ++或任何其他类型)。 我尝试使用de strtok函数,但事实certificate这只适用于每个单词之间的限制是单个字符这样的空格,分号….

我有一个变量,它是一个包含html代码的字符串,如下所示:

  Index of /davidgoudet  
Apache mod_fcgid/2.3.6 mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635 Server at turpialdevelopment.com Port 80

而且我希望在hrefrio,Oferta,Registro之类的href标签之间有一个块,但当我尝试使用strtok(字符串,“href”)时,它给了我一些奇怪的结果,这不是我正在寻找的那个。

有任何想法吗? 谢谢

strtok采用一个包含所有可能分隔符的char数组,并根据这些字符中的任何一个进行分割(在您的情况下,分割为href ),这可能就是您看到奇怪行为的原因。

您是否有理由不使用HTML解析库来提取名称?

libxml html解析器非常好: http : //www.xmlsoft.org/html/libxml-HTMLparser.html

为什么不使用正确的HTML解析器? lib2xml在C中有一个很好的HTML解析器 。

这是我的解决方案,我希望能解决您的问题。

 int split(char ***dst, char *str, char spliter) { int str_num = 0; int each_size; int index = 0; int str_index = 0; int start_index = 0; while (str[index] != '\0') { if (str[index] == spliter) { str_num++; index++; while(str[index] == spliter) { index++; } } else { index++; } } str_num++; *dst = (char **) malloc((str_num + 1)*sizeof(char*)); index = 0; while (str[index] != '\0') { if (str[index] != spliter) { start_index = index; each_size = 0; while (str[index] != spliter && str[index] != '\0') { index++; each_size++; } (*dst)[str_index] = (char*) malloc((each_size + 1)*sizeof(char)); int cur_i = 0; while (start_index != index) { (*dst)[str_index][cur_i] = str[start_index]; start_index++; cur_i++; } (*dst)[str_index][cur_i] = '\0'; str_index++; } else { index++; } } (*dst)[str_num] = NULL; return str_num; } 

尝试使用strstr()然后偏移它返回给你的指针。

 strstr(big_string_of_tags,"href")+6; //Leaves pointer at the word you're seeking, read up until you see a double quote char. 

它不是一个非常优雅的解决方案,但如果你仅限于C,它可能是一个好的开始。

您可以使用字符串比较函数(如strnstr()来定位子字符串,例如开始和结束标记。 然后,您可以轻松计算所需子字符串的位置和长度,并使用strncpy()复制该数据。