//动态存储字符串 (堆分配)
#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;
}
C语言字符串的拼接和暴力匹配
最新推荐文章于 2024-09-04 21:39:45 发布