使用微处理器,我的内存不足,我必须以非常有效和安全的方式执行此操作。
所以我有一些来自服务器的数据,我必须找到它的标题。例如:
char *meida="+IPD,0,206:GET /setWifi:home:0545881255 HTTP/1.1 Host: 192.168.4.1" ;
我只需要setWifi:home:0545881255
。
strstr
在句子中找到字符串的出现。我如何用它来找到两个单词之间的句子?
答案 0 :(得分:5)
编辑现在提取两个关键字之间的短语。
假设您读入的数据不是字符串文字,则可以对其进行修改。此代码查找第一个关键字的位置,跳过它,然后查找下一个关键字,并截断字符串。
#include <stdio.h>
#include <string.h>
int main (void){
char meida[] ="+IPD,0,206:GET /setWifi:home:0545881255 HTTP/1.1 Host: 192.168.4.1";
char *keyworda = "GET /";
char *keywordb = " HTTP/";
char *aptr, *bptr;
aptr = strstr(meida, keyworda);
if (aptr != NULL) {
aptr += strlen(keyworda); // skip past first keyword
bptr = strstr(aptr, keywordb);
if (bptr != NULL) {
*bptr = '\0'; // truncate
printf("%s\n", aptr);
}
}
return 0;
}
节目输出:
setWifi:home:0545881255
答案 1 :(得分:1)
这取决于您是否可以修改输入字符串,如果您的解决方案更有效率。
这是两个版本,一个复制输入字符串,另一个修改它,返回子字符串。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
char *
substring_enclosed(char *const input, const char *const left, const char *const right)
{
char *result;
char *tail;
result = strstr(input, left);
if (result == NULL)
return NULL;
/* At this point `result' points to the occurrance of `left', skip
* the same number of characters of `left' and you are there
*/
result += strlen(left);
tail = strstr(result, right);
if (tail != NULL)
tail[0] = '\0';
return result;
}
char *
substring_enclosed_const(const char *const input, const char *const left, const char *const right)
{
char *result;
char *tail;
char *copy;
copy = strdup(input);
if (copy == NULL)
return NULL;
result = strstr(copy, left);
if (result == NULL)
return NULL;
/* At this point `result' points to the occurrance of `left', skip
* the same number of characters of `left' and you are there
*/
result += strlen(left);
/* You have to call `free' later and you cannot do it on the
* pointer that is a result of arithmetic above, you need the
* one returned by `strdup()'
*/
memmove(copy, result, strlen(result) + 1);
tail = strstr(result, right);
if (tail != NULL)
tail[0] = '\0';
return copy;
}
int
main(void)
{
const char *meida = "+IPD,0,206:GET /setWifi:home:0545881255 HTTP/1.1 Host: 192.168.4.1";
char writeable[] = "+IPD,0,206:GET /setWifi:home:0545881255 HTTP/1.1 Host: 192.168.4.1";
char *substr;
substr = substring_enclosed_const(meida, "GET /", " HTTP");
if (substr != NULL)
{
puts(substr);
free(substr);
}
substr = substring_enclosed(writeable, "GET /", " HTTP");
if (substr != NULL)
puts(substr);
return 0;
}