一、字符串的组成
1.数据域,字符串的内容
2.字符串的长度
二、模式匹配-暴力匹配原理
1.两个字符串一个主串一个模式串用两个指针对其进行匹配
2、两个指针所对应的值相同时继续匹配下一个
3、当出现不匹配的情况时,回溯主串的指针到刚开始起点的下一个位置,模式串回到最初的位置。
4、当主串超出索引时结束匹配,判断模式串是否在最后一个位置来检查是否完成匹配。
三、暴力匹配算法代码实现
1.初始化字符串
String* InitString(void)
{
String* S = (String*)malloc(sizeof(String));
S->data = NULL;
S->length = 0;
return S;
}
2.向字符串中增加元素
void stringAssign(String* s, char* data)
{
if (s->data)
{
free(s->data);
}
int len = 0;
char* temp = data;
while (*temp)
{
temp++;
len++;
}
if (len == 0)
{
s->data = NULL;
s->length = 0;
}
else {
temp = data;
s->length = len;
s->data = (char*)malloc(sizeof(char) * (len + 1));
for (int i = 0; i < len; i++,temp++)
{
s->data[i] = *temp;
}
}
}
3.打印字符串
void PrintString(String* s)
{
for (int i = 0; i < s->length; i++)
{
printf(i == 0 ? "%c" : "->%c", s->data[i]);
}
printf("\n");
}
4.暴力匹配算法代码实现
void Forcemach(String* master, String* sub)
{
int i = 0, j = 0;
while (i < master->length && j < sub->length)
{
if (master->data[i] == sub->data[j])
{
i++; j++;
}
else {
i = i - j + 1;
j = 0;
}
}
if (j == sub->length)
{
printf("success");
}
else printf("fail");
}
5.完整工程代码
#include<stdio.h>
#include<stdlib.h>
typedef struct String
{
char* data;
int length;
}String;
String* InitString(void)
{
String* S = (String*)malloc(sizeof(String));
S->data = NULL;
S->length = 0;
return S;
}
void stringAssign(String* s, char* data)
{
if (s->data)
{
free(s->data);
}
int len = 0;
char* temp = data;
while (*temp)
{
temp++;
len++;
}
if (len == 0)
{
s->data = NULL;
s->length = 0;
}
else {
temp = data;
s->length = len;
s->data = (char*)malloc(sizeof(char) * (len + 1));
for (int i = 0; i < len; i++,temp++)
{
s->data[i] = *temp;
}
}
}
void PrintString(String* s)
{
for (int i = 0; i < s->length; i++)
{
printf(i == 0 ? "%c" : "->%c", s->data[i]);
}
printf("\n");
}
void Forcemach(String* master, String* sub)
{
int i = 0, j = 0;
while (i < master->length && j < sub->length)
{
if (master->data[i] == sub->data[j])
{
i++; j++;
}
else {
i = i - j + 1;
j = 0;
}
}
if (j == sub->length)
{
printf("success");
}
else printf("fail");
}
int main()
{
String* string1= InitString();
String* string2 = InitString();
stringAssign(string1,"Hello world!");
stringAssign(string2, "Hello world!");
Forcemach(string1, string2);
return 0;
}