怎么用多个字符截取字符串中的一段

方案一

1.hir_finder.c 实现了逐个字符匹配的方案,test_finder.c中使用它每次输入单个字符,匹配到mac#后,取出到下一个#之间的字符串

#include <stdio.h>

#define MAX_KEY_SIZE 128

static char s_thir_finder_key[MAX_KEY_SIZE+4];

static int  s_thir_finder_key_len;
static int  s_thir_finder_match_idx;
static int  s_thir_finder_match_count;


void thir_finder_init(const char* target)
{

for( s_thir_finder_key_len = 0; 
*target != 0 && s_thir_finder_key_len < MAX_KEY_SIZE;
target++, s_thir_finder_key_len++ ) {
s_thir_finder_key[s_thir_finder_key_len] = *target;
}
s_thir_finder_match_idx = 0;
s_thir_finder_match_count = 0;
}


// return 0 when not found, >0 when found, and show how many times match
int thir_finder_step(const char new_char)
{
if( s_thir_finder_key[s_thir_finder_match_idx] != new_char )
{
s_thir_finder_match_idx=0;
}
else
{
s_thir_finder_match_idx++;
if( s_thir_finder_match_idx >= s_thir_finder_key_len ) {
s_thir_finder_match_idx = 0;
s_thir_finder_match_count++;
}
}
return s_thir_finder_match_count;
}


int main() {

const char* test = "abcdefgmac#12345678999#abcdefg";
int i, j;
char mac[16];

thir_finder_init("mac#");
for(i=0; test[i] != 0; i++) {
if( thir_finder_step( test[i] ) > 0 )
{
printf("match at:%d\n", i);
i++; // skip '#'
printf("1 test[i]:%s\n", test+i);


for( j = 0; test[i] != 0 && test[i] != '#' && j < 16; i++, j++ ) {
mac[j] = test[i];
}
mac[j] = 0;
printf("j=%d mac=%s\n", j, mac);
return 0;
}
}
printf("not found\n");
return 0;

}



方案二

2.strstr.c 中实现了简单的字符串查找,test.c中使用这几个函数匹配了mac#开头到#中间的字符串

#include <stdio.h>

int c_strlen( const char* str )

{
int i;
for( i = 0; *str != 0; str++, i++);
return i;
}


int c_memcmp( const char* mem1, const char* mem2, int len )
{
int i = 0;
for( i = 0; i < len; i++, mem1++, mem2++) {
if( (*mem1) > (*mem2) ) {
return 1;
} else if( (*mem1) < (*mem2) ) {
return -1;
}
}
return 0;
}


const char* c_strstr( const char* source_str, const char* target_str ) {
int len = c_strlen(target_str);
const char* p;
for( const char* p = source_str; *p != 0; p++ ) {
if( c_memcmp(p, target_str, len) == 0 ) {
return p;
}
}
return (const char*)0;
}

int main() {
const char* test = "abcdefgmac#12345678999#abcdefg";
const char* p;
char mac[16];
char* q = mac;


p = c_strstr(test,"mac#");
printf("1 after strstr:%s\n", p);


p += c_strlen("mac#");
printf("2 skip key:%s\n", p);


for( ; *p != '#' && *p != 0; q++, p++ ) {
*q = *p;
}
*q = 0;
printf("mac:%s\n", mac);

return 0;

}

代码复制到对应的信息软件里就可以运行了

猜你喜欢

转载自blog.csdn.net/qq_34040053/article/details/80243414
今日推荐