C语言字符串的拼接和暴力匹配
作者:互联网
//动态存储字符串 (堆分配)
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char *ch;
int length;
}HString;
//初始化
HString* InitString()
{
HString* str = (HString *)malloc(sizeof(HString));
str->ch = NULL;
str->length = 0;
return str;
}
//赋值操作
void StrAssign(HString* S,char* str)
{
int len = 0;
char* temp = str;
while (*temp != '\0') //查找str的长度用len保存
{
len++;
temp++;
}
if(len == 0)
{
printf("赋值不合法\n");
return;
}
temp = str; //temp指针回到开始位置
S->ch = (char *)malloc(sizeof(char) * (len + 1));
for (int i = 0; i < len; ++i) {
S->ch[i] = *temp;
temp++;
S->length++;
}
}
// 字符串的拼接 把T拼接到S后面
void ConCat(HString* S,HString* T)
{
int m = 0;
int n = 0;
char* lens = S->ch;
char* lent = T->ch;
while (*lens != '\0')
{
m++;
lens++;
}
m++;
while (*lent != '\0')
{
S->ch[m] = T->ch[n];
n++;
m++;
lent++;
}
printf("拼接后的结果为:");
for (int i = 0; i < m; ++i) {
printf("%c",S->ch[i]);
}
printf("拼接后的长度为;%d\n",m);
}
//打印输出字符串
void ShowString(HString* S)
{
if(S->ch == NULL)
{
printf("字符串是空串!\n");
return;
}
for (int i = 0; i < S->length; ++i) {
printf("%c ",S->ch[i]);
}
printf("字符串的长度为:%d\n",S->length);
}
// 暴力匹配 S为主串 T为模式串
void ForceMather(HString* S,HString* T)
{
int i = 0;
int j = 0;
while (i < S->length && j < T->length)
{
if(S->ch[i] == T->ch[j]){
i++;
j++;
}
else{
i = i - j + 1;
j = 0;
}
}
if( j == T->length)
{
printf("匹配成功,在主串中出现的位置为:%d\n",i - j);
}
else{
printf("匹配失败!\n");
}
}
int main()
{
HString* string1 = InitString();
HString* string2 = InitString();
StrAssign(string1,"hello world");
StrAssign(string2,"wo");
ShowString(string1);
ShowString(string2);
//ConCat(string1,string2);
ForceMather(string1,string2);
return 0;
}
标签:ch,++,HString,C语言,int,length,拼接,printf,字符串 来源: https://blog.csdn.net/junfuyou/article/details/119462025