c语言 - 我不知道如何打印句子,只在某些情况下



我在解决书中的问题时被阻止了。

问题是:

读取一个单词并向后输出字符串,然后向后输出, 如果回文与原文相同,则应打印回文。

另外,不要使用诸如string.h之类的库,而是包含stdio.h 只。

所以我创建了下面的代码。

#include <stdio.h>
int main()
{
char str[128];
char temp;
int leng = 0;
char a;
scanf("%s", str);
{
a = str;
}
while(str[leng] != '')
leng++;
for (int i = 0; i < leng/2; i++)
{
temp = str[i];
str[i] = str[leng - i - 1];
str[leng - i - 1] = temp;
}
printf("%sn", str);
{
if (a == str)
printf("palindromen");
}
return 0;
}

相反顺序的输出很容易解决,但我在打印回文的过程中被阻止了。我尝试仅在输入和输出值相同时才打印回文。

但是,如果我使用的 (a == str( 是比较地址值的代码。 另外,我认为将strcmp实现为循环会很有用,但是我找不到使用strcmp将输入值与输出值进行比较的方法。

有没有办法比较 C 中的输入和输出值?还是有没有办法只在某些情况下(输入=输出(使回文打印?

我想知道我是否可以准确地用 C 编码输入值 = 输出值。

请注意,当地址值相同时,我的代码会打印回文。所以我还没有看到:(

这是一个松散编写的未经测试的代码,应该可以解决您的问题。

char str[128];
if( fgets( str, 128, stdin ) )
{
/* I hate this but restriction on string.h 
Calculate the size of this string */
size_t s_len = 0;
char *p = str;   
for( ; *p && *p != 'n' ; p++ )
s_len++;
/* trim down nextLine characters */      
if( p && *p == 'n' ) 
{
*p = '';
}
if( s_len == 0 )
{ 
/* Should never be the case here */
exit(0);
}
/* This should handle both cases of reversing and pallindrom */
int isPallindrom = 1; /* Lets Say Yes for now*/
for( size_t i = 0, j = s_len-1; i < j ; i ++, j -- )
{
if( str[i] != str[j] )
isPallindrom = 0; // Not a pallindrom
swap( str, i, j); // Write a swap function here
} 
/* at this point you should have 
1. a reversed string in a
2. based on isPallindrom value a confirmation if it really a pallindrom */
}

例如,您的代码中存在一些基本错误

a = str; 
if (a == str)

在编译时打开警告,以便在执行之前捕获这些警告。

编辑 - 为您swap

void swap( char *s, size_t i, size_t j )
{ 
char t = s[i];
s[i] = s[j];
s[j] = t;
}

使用此函数:

int compare(char *str1, char *str2)
{
while(*str1 && *str2){
if(*str1 ==  *str2){
str1++;
str2++;
}
else return (*str2 - *str1);
}
if(*str1)
return -1;
if(*str2)
return 1;
return 0;
}

逻辑:

在其中一个字符串中遇到"\0"之前,请检查任一字符串中的字符。如果字符相等,请继续。否则,如果字符串 1 中的字符>字符串 2 返回负数,如果字符串 1 中的字符

遇到"\0"后,检查 string1 是否有更多字符。如果是,则它是较大的字符串,因此返回负数。 如果 string1 没有更多字符,请检查字符串 2。如果也没有更多字符,则返回 0。否则返回正数。

相关内容

最新更新