1 #include<stdio.h>
2
3 int strLength(char* s)//求字符长度
4 {
5 int i=0;
6 while(s[i]!=NULL)
7 {
8 i++;
9 }
10 return i;
11 }
12
13 int* getNext(char* p)
14 {
15 int length=strLength(p);
16 int* next=(int *)calloc(length,sizeof(int));
17 next[0] = -1;
18 int j = 0;
19 int k = -1;
20 while (j < length - 1)
21 {
22 if (k == -1 || p[j] == p[k])
23 {
24 if (p[++j] == p[++k])
25 { // 当两个字符相等时要跳过
26
27 next[j] = next[k];
28 }
29 else
30 {
31 next[j] = k;
32 }
33 }
34 else
35 {
36 k = next[k];
37 }
38 }
39 return next;
40 }
41
42 int KMP(char* t,char* p)
43 {
44 int i = 0; // 主串的位置
45 int j = 0; // 模式串的位置
46 int lengtht=strLength(t);
47 int lengthp=strLength(p);
48 int *next=getNext(p);
49
50
51 while (i < lengtht && j < lengthp)
52 {
53 if (j == -1 || t[i] == p[j])
54 { // 当j为-1时,要移动的是i,当然j也要归0
55 i++;
56 j++;
57 }
58 else
59 {
60 // i不需要回溯了
61 // i = i - j + 1;
62 j = next[j]; // j回到指定位置
63 }
64 }
65
66 if (j == lengthp)
67 {
68 return i - j;
69 }
70 else
71 {
72 return -1;
73 }
74 }
75
76
77 void strCopy(char *des,char *src)//字符串拷贝
78 {
79 int i=0;
80 while(src[i]!=NULL)
81 {
82 des[i]=src[i];
83 i++;
84 }
85 }
86
87 void destroyStr(char *des)//字符串删除
88 {
89 free(des);
90 }
91
92 bool strEmpty(char *des)//判断字符串是否为空
93 {
94 if(des[0]==NULL)
95 {
96 return true;
97 }
98 else
99 {
100 return false;
101 }
102 }
103
104 int strCompare(char *s1,char *s2)//字符串比较
105 {
106 int flag;
107 for(int i=0;;i++)
108 {
109 if(s1[i]==NULL&&s2[i]!=NULL)
110 {
111 flag=-1;
112 break;
113 }
114 else if(s1[i]!=NULL&&s2[i]==NULL)
115 {
116 flag=1;
117 break;
118 }
119 else if(s1[i]==NULL&&s2[i]==NULL)
120 {
121 flag=0;
122 break;
123 }
124 }
125 return flag;
126 }
127
128 char* strConcat(char* s1,char* s2)//字符串连接函数
129 {
130 int length1,length2;
131 length1=strLength(s1);
132 length2=strLength(s2);
133 char *s=(char *)malloc(sizeof(char)*(length1+length2));
134 int i=0;
135 while(s1[i]!=NULL)
136 {
137 s[i]=s1[i];
138 i++;
139 }
140 int j=0;
141 while(s2[j]!=NULL)
142 {
143 s[i]=s2[j];
144 i++;
145 j++;
146 }
147 return s;
148 }
149
150 char* strSub(char* s,int pos,int length)//将str串从pos位置开始复制到subStr中
151 {
152 char *sub=(char *)malloc(sizeof(char)*length);//建议此处将malloc函数改为calloc函数;calloc在动态分配完内存后,自动初始化该内存空间为零,而malloc不初始化,里边数据是随机的垃圾数据。
153 int i=pos;
154 int count=0;
155 while(count<=length)
156 {
157 sub[count]=s[i];
158 i++;
159 count++;
160 }
161 return sub;
162 }
163
164 char* strReplace(char* s,char* sub,char* replaceStr)//字符串替换
165 {
166 int end;
167 char* temp1;
168 char* temp2;
169 int begin=0;
170 int subLength=strlen(sub);
171 end=KMP(s,sub);
172 while(end!=-1)
173 {
174 temp1=strSub(s,begin,end-begin);
175 temp2=strSub(s,end+subLength,strlen(s)-(end+subLength));
176 s=strcat(temp1,replaceStr);
177 s=strcat(s,temp2);
178 end=KMP(s,sub);
179 }
180 return s;
181 }