检查字符串是否在C中是回文 [英] Check if a string is palindrome in C
问题描述
我对我正在练习的这段代码有疑问.我必须检查一个字符串是否是回文.我无法更改该函数的声明.只有当所有字母都相同时该函数才返回1(例如"aaaa"),但是如果我将该句子归类为其他回文(例如"anna"),则该函数返回0,我不知道为什么会这样.谢谢!
i've a question about this code i'm writing for an exercise. I've to check if a string is palindrome. I can't change the declaration of the function.The function only return 1 when all the letters are the same (like "aaaa") but if i charge the sentence with other palindrome (like "anna") the function return me 0 , i can't figure out why this appening.Thank you!
char* cargar (char*);
int pali (char*);
int main()
{
char*texto=NULL;
texto=cargar(texto);
int res=pali(texto);
if(res==1){printf("\nPalindrome");}
else printf("\nNot palindrome");
return 0;
}
char* cargar (char*texto)
{
char letra;
int i=0;
texto=malloc(sizeof(char));
letra=getche();
*(texto+i)=letra;
while(letra!='\r'){
i++;
texto=realloc(texto,(i+1)*sizeof(char));
letra=getche();
*(texto+i)=letra;}
*(texto+i)='\0';
return texto;
}
int pali (char* texto)
{
int i;
for(i=0;*(texto+i)!='\0';i++){
}i--;
if(i==0||i==1){return 1;}
if(*texto==*(texto+i)){
return pali(++texto);
}
else return 0;
}
推荐答案
确定字符串是否为回文式的函数的想法不完善.
Your function to determine whether a string is a palindrome is not well thought out.
假设您的字符串s
的长度为l
.字符串中的字符布局为:
Let's say you have a string s
of length l
. The characters in the string are laid out as:
Indices: 0 1 2 3 l-4 l-3 l-2 l-1
+----+----+----+----+- ... -+----+----+----+----+
| | | | | ... | | | | |
+----+----+----+----+- ... -+----+----+----+----+
如果字符串是回文,
s[0] = s[l-1]
s[1] = s[l-2]
...
当LHS的索引大于或等于LHS时,您可以停止检查. RHS的索引.
You can stop checking when the index of the LHS is greater or equal to the index of the RHS.
要将其转换为代码,
int is_palindrome(char const* s)
{
size_t len = strlen(s);
if ( len == 0 ) // An empty string a palindrome
{
return 1;
}
size_t i = 0;
size_t j = len-1;
for ( ; i < j; ++i, --j )
{
if ( s[i] != s[j] )
{
// the string is not a palindrome.
return 0;
}
}
// If we don't return from inside the for loop,
// the string is a palindrome.
return 1;
}
这篇关于检查字符串是否在C中是回文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!