关闭

串(功能:插入、串匹配)——简单匹配算法

111人阅读 评论(0) 收藏 举报
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 20


typedef struct {
char str[MAXSIZE];
int len;
}SString;


SString *StrInit();
SString *StrInsert();
void Print();
int StrIndex();




void main () {
int i;
SString *s = NULL;
SString *t = NULL;
// SString *v = NULL;
s = (SString *)malloc(sizeof(SString));
t = (SString *)malloc(sizeof(SString));
// v = (SString *)malloc(sizeof(SString));
s = StrInit(s);
printf("\n输出s = %d\n",s->len);
Print(s);
t = StrInit(t);
printf("\n输出t = %d\n",t->len);
Print(t);
// printf("请设置插入点:");
// scanf("%d",&i);
// s = StrInsert(s,i,t);
// printf("\n输出s = %d\n",s->len);
// Print(s);
printf("\n%d\n",StrIndex(s,t,1)+1);
}


SString *StrInit(SString *s) {
int i;
printf("请设置串的长度:");
scanf("%d",&s->len);
for (i = 0; i < s->len; i++) {
printf("第%d个字符:",i+1);
scanf("%d",&s->str[i]);
}
printf("\n");
return s;
}


SString *StrInsert(SString *s, int pos, SString *t) {
int i,j;
if (pos < 1||pos >s->len+1) return 0;
if (s->len + t->len <= MAXSIZE) {
for (i = s->len + t->len, j = 0; i > s->len; i--,j++) {
s->str[i-1] = s->str[i-t->len-1] ; 
printf("\nj = %d\n",j);
}
for (i = 0; i < t->len; i++) {
s->str[pos+i+-1] = t->str[i] ;
}
s->len = s->len + t->len ;
}
else {
if (pos + t->len > MAXSIZE){
for (i = pos-1, j = 0; i <= MAXSIZE-1; i++, j++) {
s->str[i] = t->str[j] ;
}
}
else {
for (i = MAXSIZE; i >= t->len+pos-1; i--){
s->str[i-1] = s->str[i-t->len-1] ;
}
for (i = 0; i < t->len; i++) {
s->str[pos+i-1] = t->str[i] ;
}
}
s->len = MAXSIZE ;
}
return s;
}


void Print(SString *s) {
int i;
printf("**********************************\n");
for (i = 0; i < s->len; i++) {
printf("第%d个字符 = %d\n",i+1,s->str[i]);
}
}


int StrIndex(SString *s, SString *t, int pos) {
int i,j,start;
if (t->len == 0) {
return 0;
}
start = pos;
i = start;
j = 0;
while (i < s->len && j < t->len) {
if (s->str[i] == t->str[j]) {
i++;
j++;
}
else {
start++;
i = start;
j = 0;
}

if (j >= t->len) {
return start;
}
else {
return -1;
}
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1246次
    • 积分:106
    • 等级:
    • 排名:千里之外
    • 原创:9篇
    • 转载:0篇
    • 译文:1篇
    • 评论:0条