gpt4 book ai didi

递归函数上的 char * 数组操作

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:59:22 25 4
gpt4 key购买 nike

我有一个程序可以计算两个字符串的编辑距离。它还输出所有编辑操作以获得完整的转换。我写了一个递归函数来探索由编辑距离计算函数填充的矩阵并重建路径

void reconstruct_path(char *s1, char *s2 ,int i, int j , matrix_t 矩阵)

 void reconstruct_path(char *s1, char *s2 int i, int j , matrix_t matrix)
{
if(matrix[i][j].parent == -1) return;


if (matrix[i][j].parent == MATCH)
{
reconstruct_path(s1,s2,i-1,j-1,matrix);
match_out(s1, s2 , i, j);
return;
}

if (matrix[i][j].parent == INSERT)
{
reconstruct_path(s1,s2,i,j-1,matrix);
insert_out(s2, j);
return;
}

if (matrix[i][j].parent == DELETE)
{
reconstruct_path(s1,s2,edit,i-1,j,matrix);
delete_out(s1, i);
return;
}

}`

你可以注意到这个函数调用了三个函数

- void match_out(char *s1, char *s2,int i, int j)
- void insert_out(char *t, int j)
- void delete_out(char *s, int i)

void match_out(char *s1, char *s2, int i, int j)

void match_out(char *s1, char *s2 ,int i, int j)
{
if (s1[i] == s2[j])
{
printf("M no edit needed \n" );
}
else
{
printf("S subst %c with %c \n",s1[i] , s2[j]);
}
}

void insert_out(char *t, int j)

void insert_out(char *t, int j)
{
printf("I Insert %c\n",t[j]);
}

void delete_out(char *s, int i)

void delete_out(char *s, int i)
{
printf("D delete %c\n",s[i]);
}

这会产生这样的输出

from "parent" to "cousin" :

S subst p with c
S subst a with o
S subst r with u
S subst e with s
S subst n with i
S subst t with n

我想改进它以获得更精确的输出:

from "parent" to "cousin" :

S subst p with c parent -> carent
S subst a with o carent -> corent
S subst r with u corent -> couent
S subst e with s couent -> cousnt
S subst n with i cousnt -> cousit
S subst t with n cousit -> cousin

你有什么建议吗? (我不太擅长 C 字符串操作)


[从评论更新到 this answer :]

s1s2 中收到的两个字符串的数据类型是什么? (由 vj1207 询问)

它们在 main() 中声明如下 char *str_a = "parent"; char *str_b = "表弟";

最佳答案

你可以在ma​​tch_out中添加几行

void match_out(char *s1, char *s2, char **edit ,int i, int j)
{
if (s1[i] == s2[j])
{
printf("M no edit needed \n" );
}
else
{
printf("S subst %c with %c ",s1[i] , s2[j]);
//**from here**
printf("%s -> ",s1);
s1[i]=s2[j];
printf("%s\n",s1);
//upto here
}
}

更新

您可以将 char 数组声明为

char str[]= {'p','a','r','e','n','t'};

如果你声明它为

char * str = "parent";

那你就不能修改了。这就是您收到上述错误的原因。

关于递归函数上的 char * 数组操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25971991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com