使用微處理器,我跑出來的內存,我不得不這樣做在一個非常有效和安全的方式。查找字符串之間的字符串中有效的方式
所以我有一些數據從服務器來了,我一定要找到它的頭。例如:
char *meida="+IPD,0,206:GET /setWifi:home:0545881255 HTTP/1.1 Host: 192.168.4.1" ;
我只需要得到setWifi:home:0545881255
。
strstr
發現在一個句子串的發生。我怎樣才能用它找到2個單詞之間的句子?
使用微處理器,我跑出來的內存,我不得不這樣做在一個非常有效和安全的方式。查找字符串之間的字符串中有效的方式
所以我有一些數據從服務器來了,我一定要找到它的頭。例如:
char *meida="+IPD,0,206:GET /setWifi:home:0545881255 HTTP/1.1 Host: 192.168.4.1" ;
我只需要得到setWifi:home:0545881255
。
strstr
發現在一個句子串的發生。我怎樣才能用它找到2個單詞之間的句子?
編輯現在提取兩個關鍵詞之間的短語。
假設您讀入的數據是而不是是一個字符串文字,它可以被修改。該代碼找到第一個關鍵字的位置,跳過它,然後找到下一個關鍵字,並截斷該字符串。
#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
這取決於你是否可以修改輸入的字符串或沒有,如果你能解決的辦法是更有效的。
這裏有兩個版本,一個是將複製修改到位返回字符串輸入字符串和一個。
#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;
}
這不是OP想要什麼。 –
@iharob輸出的是OP引用的消息... –
但它沒有提取兩個字符串之間的子字符串。 –