gpt4 book ai didi

c - C 编程简介 - [期末考试示例] 回文函数

转载 作者:行者123 更新时间:2023-11-30 21:39:22 32 4
gpt4 key购买 nike

我需要帮助!我做不到。我尝试了很多方法但没有奏效。至少有人可以帮我解决逻辑问题。下面我将粘贴我的代码。

  • 开发一个带有接收字符数组的函数的程序。该函数必须修改原始文本并将其精确复制到另一个文本,但在每个回文单词前添加两个星号 (**),回文是向后或向前读相同的单词(例如 ANNA、KAYAK)。

例如,我最好的 friend 安娜有一艘红色皮划艇

我最好的 friend **安娜有一艘红色**皮划艇。

#include <stdio.h>
#include <stdlib.h>

void Cargar(char texto1[])
{
int i=0;
char letra;

do
{
letra=getche();
if(letra != '.')
{
texto1[i]=letra;
i++;
}
}
while (letra != '.' && i<99);

texto1[i]='\0';

}


int main()
{
char texto1[100], texto2[100];
printf("Ingrese texto: ");
Cargar(texto1);

int pos=0, esp_anterior=0, aux1=0, aux2=0, aux3=0, bandera=0;
int i, j, k;

for(pos = 0 ; texto1[pos] != '\0' ; pos++)
{
if( texto1[pos] == ' ')
{
if(bandera==0)
{
if( hay_palindromo(texto1, pos, esp_anterior) == 1)
{
texto2[0]='*';
texto2[1]='*';

for(i=2, j=0; j<pos ; j++ , i++)
{
texto2[i]=texto1[j];
}
aux1=i;
aux2=j;
}
else
{
for(i=0; i<pos; i++)
{
texto2[i]=texto1[i];
}
aux3=i;
}
bandera = 1;
esp_anterior = pos;
}

else

{
if(bandera == 1)
{
if( hay_palindromo(texto1, pos, esp_anterior) == 1)
{

texto2[aux1]='*';
texto2[aux1+1]='*';

for(i=aux1+2, j=aux2; j<pos ; j++ , i++)
{
texto2[i]=texto1[j];
}
aux1=i;
aux2=j;

}
else
{
for(i=aux3; i<pos; i++)
{
texto2[i]=texto1[i];
}
aux3=i;

}
esp_anterior=pos;

}
}

}
}
printf("\n%s", texto2);

return 0;
}

int hay_palindromo(char texto1[], int pos, int esp_anterior)
{
int i, j, bandera=0;
for(i=esp_anterior, j=pos; i<pos; i++, j--)
{
if(texto1[i] == texto1[j])
{
bandera=1;
}
else
{
bandera=0;
break;
}
}
if(bandera==1)
{
return 1;
}
else
{
return 0;
}
}

最佳答案

我建议这样的逻辑:

获取字符串,用分隔符分隔它 - 在您的情况下使用 strtok 分隔符 - “”(空格)。

然后,将每个分隔单词发送到一个函数,该函数确定该字符串是否为回文。

如果字符串是回文,请为字符串+“”分配足够的空间,并将“”+字符串复制到分配的空间中,保存“光标”在该数组上的当前位置。伪示例:

"Anna notpali"
char *new_str;
int cursor = 0;

is_palindrome("Anna")
Yes -> new_str = malloc(strlen("Anna") + strlen("**") + 1)
strcpy(&(new_str[cursor]),"**Anna");
cursor += strlen("**Anna");

is_palindrom("notpali")
No -> new_str = realloc(new_str,strlen(" notpali") + 1)
strcpy(&(new_str[cursor])," notpali");
cursor += strlen(" notpali");

// After going through all the words
new_str[cursor] = '\0'

等等,可能有一些极端情况需要处理,但这是我建议处理它的基本逻辑。

关于c - C 编程简介 - [期末考试示例] 回文函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34321022/

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