我正在尝试创建文本编辑器的功能,例如 - 插入,删除和设置。我的文本编辑器中的每个单词都由行号表示。例如,如果我有"你好吗?" ,它由
表示1- hi
2- how
3- are
4- you
其中1,2,3,4表示行号(索引)。这是我的基本代码,我将从这里开始构建功能。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct text{
int index;
char *word;
} text;
void add_word(text *t,char *word)
{
// adds the word at the last line
}
void insert(text *t, int index, char *word_to_insert)
{
// inserts the word at the index
}
int main() {
char text[256];
// allocates memory where all words of the text editor will be stored
text *pointer_to_text=(text *)malloc(sizeof(text *));
char text_insert[256];
while ((nextop = getchar()) != 'q') {
if (nextop == 'a') {
new_line = strcpy(text, "hello");
add_word(point_to_text, new_line);
}
if (nextop == 'i') {
index = 5;
new_line=strcpy(text_insert,"change");
insert_word(point_to_text,index,new_line);
}
}
}
return (0);
}
根据这个,我在text[]
数组中存储一个单词并将其传递给add
函数。当我插入一个新单词时,我使用text_insert[]
数组,在其中存储一个单词并将其发送到该函数。在插入结束时,索引将附加text_insert[]
中的单词。我使用指针来引用text_insert[]
的地址。指向此地址的指针存储在我执行插入的索引处
我的问题是如果我想插入另一个单词怎么办?我假设我必须创建一个新的char array[]
并将指针存储到索引的array[]
。
那么我每次都要创建一个新的数组还是有更好的方法呢?请指教。