总的实现代码:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
// 定义链式存储的字符节点
typedef struct CharNode {
char data; // 存储字符
struct CharNode* next; // 指向下一个节点
} CharNode;
// 定义字符串结构
typedef struct {
CharNode* head; // 指向链表的头节点
int length; // 字符串长度
} String;
// 初始化字符串
void InitStr(String* str)
{
str->head = NULL;
str->length = 0;
}
// 释放字符串内存
void StrFree(String* str)
{
CharNode* current = str->head;
CharNode* nextNode;
while (current != NULL)
{
nextNode = current->next;
free(current);
current = nextNode;
}
str->head = NULL;
str->length = 0;
}
// 从 C 字符串初始化链式字符串
void StrCopy(String* str, const char* cstr)
{
InitStr(str);
if(*cstr == '\0') // 判断不是空字符
return;
CharNode *p = NULL;
CharNode* newNode = (CharNode*)malloc(sizeof(CharNode));
newNode->data = *cstr++;
newNode->next = str->head;
str->head = newNode; // 插入到链表头部
p = newNode;
while (*cstr)
{
CharNode* Node = (CharNode*)malloc(sizeof(CharNode));
Node->data = *cstr++;
p->next = Node;
Node->next = NULL;
p = Node; // 插入到链表头部
str->length++;
}
}
// 计算字符串长度
int stringLength(String* str)
{
return str->length;
}
// 字符串拼接
void StrCat(String* dest, const String* src)
{
CharNode* current = src->head;
while (current != NULL)
{
CharNode* newNode = (CharNode*)malloc(sizeof(CharNode));
newNode->data = current->data;
newNode->next = NULL;
// 将新节点添加到目标字符串的尾部
if (dest->head == NULL)
{
dest->head = newNode; // 如果目标字符串为空
}
else
{
CharNode* tail = dest->head;
while (tail->next != NULL)
{
tail = tail->next; // 找到尾部
}
tail->next = newNode; // 添加新节点
}
dest->length++;
current = current->next;
}
}
// 查找子字符串
int StrFind(const String* str, const char* substring)
{
CharNode* current = str->head;
CharNode* subCurrent;
int index = 0;
while (current != NULL)
{
subCurrent = current;
int subIndex = 0;
// 检查是否匹配子字符串
while (subCurrent != NULL && substring[subIndex] != '\0' && subCurrent->data == substring[subIndex])
{
subCurrent = subCurrent->next;
subIndex++;
}
// 如果匹配到子字符串的末尾
if (substring[subIndex] == '\0')
{
return index; // 返回起始位置
}
current = current->next;
index++;
}
return -1; // 未找到
}
// 显示字符串
void StrShow(const String* str)
{
CharNode* current = str->head;
while (current != NULL)
{
putchar(current->data);
current = current->next;
}
putchar('\n');
}
// 主函数示例
int main()
{
String str1;
StrCopy(&str1, "Hello");
StrCopy(&str1, "hello");
StrShow(&str1);
String str2;
StrCopy(&str2, " World!");
printf("字符串1: ");
StrShow(&str1);
printf("字符串2: ");
StrShow(&str2);
// 拼接字符串
StrCat(&str1, &str2);
printf("拼接后的字符串: ");
StrShow(&str1);
// 查找子字符串
const char* substring = "lo";
int position = StrFind(&str1, substring);
if (position != -1)
{
printf("子字符串 \"%s\" 在位置 %d\n", substring, position);
}
else
{
printf("子字符串 \"%s\" 未找到\n", substring);
}
// 释放内存
StrFree(&str1);
StrFree(&str2);
return 0;
}
没有回复内容