#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define BLOCK_SIZE 4 // 可由用户定义的块大小
#define BLS_BLANK '#' // 用于空白处的补齐字符
#define bool int
#define true 1
#define false 0
typedef struct _block
{
char ch[BLOCK_SIZE]; //块的数据域
struct _block *next; //块的指针域
} Block;
typedef struct
{
Block *head; // 串的头指针
Block *tail; // 串的尾指针
int len; // 串的当前长度
} BLString;
void blstr_init(BLString *T);//初始化
void CreatBLS(BLString *T); //创建
void PrintBLS(BLString *T); //输出
int blstr_substr(BLString src, int pos, int len, BLString* sub); //查找
/*src为要查找的字符串,pos为子串开始的下标,len为子串的长度*/
/*sub在函数调用运行前指向一个已经初始化好的空串,在函数返回时,sub指向串src从第pos个字符起长度为len的子串*/
/*函数查找成功返回true,参数不正确返回 false*/
//字符串初始化函数:
void blstr_init(BLString *T)
{
T->len = 0;
T->head = NULL;
T->tail = NULL;
}
int main()
{
int pos=14, len=4;
int flag=0;
BLString src, sub;
blstr_init(&src); //初始化
blstr_init(&sub);
CreatBLS(&src); //创建原字符串
//PrintBLS(&src);
flag=blstr_substr(src, pos, len, &sub);
if(flag)
PrintBLS(&sub);
return 0;
}
void PrintBLS(BLString *T)
{
int n, i=0;
int flag=0; //计数
Block *bl=T->head;
n = T->len / BLOCK_SIZE;
if (T->len % BLOCK_SIZE)
n++;
printf("字串长度:%d\n", T->len);
while(bl->ch[i]!='#')
{
printf("flag: %d bl->ch[%d]: %c\n", flag, i, bl->ch[i]);
i++;
flag++;
if(flag>=T->len)
break;
if(i==BLOCK_SIZE)
{
i=0;
bl=bl->next;
}
}
printf("\n");
}
void CreatBLS(BLString *T)
{
char str[]="abcdefghijklmno";
int k=0, m=0; //k为ch的下标,m为str的下标
int len=strlen(str), n=0;//n为块的个数
Block *front, *rear; //创造头尾指针
int flag=0;
n = len / BLOCK_SIZE;
if (len % BLOCK_SIZE)
n++;
front = (Block*)malloc(sizeof(Block)); //创建头节点
(*T).head=front; //头指针指向头节点
for(int i=0;i<len;i++)
{
rear=(Block*)malloc(sizeof(Block));
for(k=0;k<BLOCK_SIZE&&m!=len;k++)
{
(*rear).ch[k]=str[m++];
}
front->next = rear;
front = rear;
}
rear->next=NULL;
for (m = len % BLOCK_SIZE; m < BLOCK_SIZE; m++)
rear->ch[m] = BLS_BLANK;
(*T).tail=rear;
(*T).len = len;
(*T).head=(*T).head->next;
Block *t=front;
front=front->next;
free(t);
}
bool blstr_substr(BLString src, int pos, int len, BLString* sub)
{
Block *front, *rear; //创造头尾指针
int n=0; //n为块的个数
int src_len=0; //src下标
int i=0;
Block* sh=src.head;
if(len>src.len-pos)
len=src.len-pos;
if (pos < 0 || pos >= src.len || len <= 0)
return false;
n = len / BLOCK_SIZE;
if (len % BLOCK_SIZE)
n++;
//寻找src中的字符
for(i=0;i<pos/BLOCK_SIZE;i++)
{
sh=sh->next;
src_len+=BLOCK_SIZE;
}
int src_k=pos-src_len;
front = (Block*)malloc(sizeof(Block)); //创建头节点
(*sub).head=front; //头指针指向头节点
for (i = 0; i < n; i++) {
rear = (Block*)malloc(sizeof(Block));
for(int k=0;k<BLOCK_SIZE;k++)
{
(*rear).ch[k]=sh->ch[src_k++];
src_len++;
if(src_k==BLOCK_SIZE)
{
sh=sh->next;
src_k=0;
}
if(src_len==pos+len)
break;
}
front->next = rear;
front = rear;
}
rear->next = NULL;
if(len%BLOCK_SIZE)
for (n = len % BLOCK_SIZE; n < BLOCK_SIZE; n++)
rear->ch[n] = BLS_BLANK;
(*sub).tail=rear;
(*sub).len = len;
(*sub).head=(*sub).head->next;
front=front->next;
return true;
}
如果有更好的方法或者以上程序有任何错误,欢迎讨论。