字符串定义:由零个或多个字符组成的有限序列
字符串的比较:一般只比较是否相等(可比大小,比相同位置上的字符的ASCII值)
字符串的存储结构:
顺序存储:数组
链式存储:链表
BF算法:Brute Force,朴素的模式匹配算法
核心思想:
有两个字符串S和T,长度为N和M。首先S[1]和T[1]比较,若相等,则再比较S[2]和T[2],一直到T[M]
为止;若S[1]和T[1]不等,则T向右移动一个字符的位置,再依次进行比较
BF算法实例:
#include <stdio.h>
#include <stdlib.h>
void BruteForce(char mstr[], char str[])
{
int i = 0, j = 0;
int len = 0, count = 0;
while( '\0' != str[j] )
{
len++;
j++;
}
j = 0;
while( '\0' != str[j] )
{
if(str[j] == mstr[i])
{
j++;
i++;
count++;
}
else
{
if( 0 != j)
{
j = 0;
count = 0;
}
else
{
i++;
}
}
if( count == len )
{
printf("\nThe main string concludes the string!\n");
break;
}
if( '\0' == mstr[i] && count != len )
{
printf("\nThe main string does not conclude the string!\n");
break;
}
}
}
void print(char str[])
{
int i = 0;
while( '\0' != str[i] )
{
printf("%c", str[i]);
i++;
if( '\0' == str[i] )
{
printf("\n");
}
}
}
int main(void)
{
char mstr[20], str[10];
char c;
int i = 0, j = 0;
printf("Please enter the main string (within 20) and enter # to end:\n");
scanf("%c", &c);
while( '#' != c )
{
mstr[i] = c;
mstr[i+1] = '\0';
i++;
scanf("%c", &c);
}
printf("\nPlease enter the string (within 10) and enter # to end:\n");
fflush(stdin);
scanf("%c", &c);
while( '#' != c )
{
str[j] = c;
str[j+1] = '\0';
j++;
scanf("%c", &c);
}
printf("\n");
//print(mstr);
//print(str);
BruteForce(mstr, str);
return 0;
}
KMP算法:
#include <stdio.h>
#include <stdlib.h>
#define MAXBUFFER 30
typedef struct String
{
int len;
char str[MAXBUFFER];
}Str;
//i:前缀
//j:后缀
void get_next(Str T, int *next)
{
int j = 0;
int i = 1;
next[1] = 0;
while( i < T.len )
{
if( 0 == j || T.str[i] == T.str[j] )
{
i++;
j++;
if(T.str[i] == T.str[j]) //出现连续重复的情况,next数组中的数字与上一个相同
{
next[i] = next[j];
}
else
{
next[i] = j;
}
}
else
{
j = next[j];
}
}
}
int index_KMP(Str T, Str S) //返回子串T在主串S第pos个字符之后的位置
{
int i = 1, j = 1;
int *next[MAXBUFFER];
get_next(T, next);
while( i <= S.len && j <= T.len )
{
if(0 == j || S.str[i] == T.str[j])
{
i++;
j++;
}
else
{
j = next[j];
}
}
if(j > T.len)
{
return i - T.len;
}
else
{
return 0;
}
}
int main(void)
{
Str T, S;
T.len = 0;
S.len = 0;
int i = 1;
int pos;
char c;
printf("Please enter the string of S, and enter # to end:\n");
scanf("%c", &c);
while( '#' != c )
{
S.str[i] = c;
S.str[i+1] = '\0';
i++;
S.len++;
scanf("%c", &c);
}
S.str[0] = ' ';
i = 1;
printf("Please enter the string of T, and enter # to end:\n");
fflush(stdin); //清除缓存换行键
scanf("%c", &c);
while( '#' != c )
{
T.str[i] = c;
T.str[i+1] = '\0';
i++;
T.len++;
scanf("%c", &c);
}
T.str[0] = ' ';
pos = index_KMP(T, S);
printf("The start of the substring is at the %d th position of the main string\n", pos);
return 0;
}