为什么字符串不相等?
#include "usefunc.h"
#define MY_SIZE 256
int inpArr(char tmp[], int size) {
size = -1;
while(1) {
size++;
if((tmp[size] = getchar()) == '\n') break;
}
return size;
}
void revString(char tmp[], int size, char new[]) {
int i, j;
for (i = size, j = 0; i >= 0; i--, j++) new[j] = tmp[i];
}
void copy_forw(char tmp[], int size, char new[], int offset) {
int i, j;
for (i = offset, j = 0; i <= size; i++, j++) new[j] = tmp[i];
}
void copy_back(char tmp[], int size, char new[], int offset) {
int i, j;
for (i = size-offset, j = size; i > -1; i--, j--) new[j] = tmp[i];
}
void cut(char tmp[], int size, char new[]) {
}
int main () {
char tmp[MY_SIZE] = {0x0}, rev[MY_SIZE] = {0x0}, new[MY_SIZE] = {0x0}, some[MY_SIZE-1];
int size = inpArr(tmp, size);
revString(tmp, size, rev);
copy_forw(rev, size, new, 1); copy_back(tmp, size, some, 1);
printf("|%s|\n|%s|\n", some, new);
int is_palindrome = StringEqual(new, some);
printf("%d\n", is_palindrome);
}
StringEqual 基本上是一个仅逐个字符比较 char 数组的函数。
如果我输入字符串 yay
它应该是一个回文,但似乎不是。这是为什么呢?
#include "usefunc.h"
#define MY_SIZE 256
int inpArr(char tmp[], int size) {
size = -1;
while(1) {
size++;
if((tmp[size] = getchar()) == '\n') break;
}
return size;
}
void revString(char tmp[], int size, char new[]) {
int i, j;
for (i = size, j = 0; i >= 0; i--, j++) new[j] = tmp[i];
}
void copy_forw(char tmp[], int size, char new[], int offset) {
int i, j;
for (i = offset, j = 0; i <= size; i++, j++) new[j] = tmp[i];
}
void copy_back(char tmp[], int size, char new[], int offset) {
int i, j;
for (i = size-offset, j = size; i > -1; i--, j--) new[j] = tmp[i];
}
void cut(char tmp[], int size, char new[]) {
}
int main () {
char tmp[MY_SIZE] = {0x0}, rev[MY_SIZE] = {0x0}, new[MY_SIZE] = {0x0}, some[MY_SIZE-1];
int size = inpArr(tmp, size);
revString(tmp, size, rev);
copy_forw(rev, size, new, 1); copy_back(tmp, size, some, 1);
printf("|%s|\n|%s|\n", some, new);
int is_palindrome = StringEqual(new, some);
printf("%d\n", is_palindrome);
}
StringEqual is pretty much a function that just compares a char array character by character.
If I input the string yay
it should be a palindrome, but doesn't appear to be. Why is this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的问题在于以下行:
该行始终将用户输入的字符分配到数组中,即使用户输入
\n
字符来指示他们已完成提供输入。例如,当您输入“yay”,然后输入换行符来指示您已完成时,您的数组看起来像:而该数组的反向是:
...这显然会导致回文检查失败。我建议修改您的代码如下:
Your problem is with the line that goes:
This line will always assign the character the user inputs into the array, even when the user inputs the
\n
character to indicate that they are done providing input. So for example, when you enter "yay" and then a newline to indicate that you are done, your array looks like:and the reverse of that array is:
...which will obviously fail a palindrome check. I would suggest revising your code as follows:
查看行:
'\n'
始终出现在字符串的末尾。那是你的问题。Look at line:
'\n'
is always present at the end of the string. That's your problem.