美好的一天! 我们的老师要求我们确定一个单词或一系列数字是否是使用堆栈的回文。我已经完成了那个。但是我现在想练习更多我试图通过删除空格和其他不相关的字符来判断一个句子是否是回文(注意:不再是我的作业的一部分)我的代码已经在工作(希望)但我发现它凌乱。所以我想改进它。我想删除goto功能,因为我的老师建议我不要使用它。如何使用goto函数退出if语句?先感谢您。还有其他方法可以检查句子是否是回文,因为我的代码是用强力方法完成的。我的代码如下:注意(我没有在这里包含/粘贴struct和pop和push函数)
int main(){
char word[11];
char temp[11];
char value;
int i=0, x=0, n=0, length=0;
Stack*head = NULL;
printf("Please type the word: ");
gets(word);
length = strlen(word);
while(i<length){
if(isspace(word[i]) || !isalpha(word[i])) {
if(isdigit(word[i])) goto NEXT; // i used the goto function here
i++;
continue;
}
NEXT:
temp[n]=word[i];
push(&head, word[i]);
i++;
n++;
}
temp[n]='\0';
while(x<n){
value = pop(&head);
if (value==temp[x]){
x++;
continue;
}
break;
}
if(x==n) printf("Yehey! It is a palindrome.");
else printf("Sorry, It is not a palindrome.");
getch();
}
根据您的建议。这是我改进的代码:
int main(){
char word[11];
char temp[11];
int i=0, n=0;
int flag = 1;
Stack*head = NULL;
printf("Please type the word: ");
fgets(word, 11, stdin);
for(i = 0; word[i]!='\0' ; i++){
if(isalnum(word[i])) {
temp[n]=word[i];
push(&head, word[i]);
n++;
}
}
temp[n]='\0';
for(i=0; temp[i]!='\0'; i++){
if (pop(&head)!=temp[i]){
flag = 0;
break;
}
}
if (flag==1) printf("Yehey! It is a palindrome.");
else printf("Sorry, It is not a palindrome.");
getch();
}
答案 0 :(得分:4)
您可以做的最简单的更改如下:
...
if(isspace(word[i]) || !isalpha(word[i])) {
if(!isdigit(word[i])) {
i++;
continue;
}
}
temp[n]=word[i];
...
您可以采取一些其他措施来整理代码(例如,合并if
语句,摆脱isspace
,因为!isalpha
涵盖了这些等等。
答案 1 :(得分:2)
我喜欢你的态度。
首先,你要做的是嵌套两个基本上是一个的逻辑语句。您还使用了错误的函数来确定字符类型:
如果isspace(word[i])
,那么您可以保证!isalpha(word[i])
。两个语句总是同时为真或假,因此其中一个是多余的。你真正做的只是推字符,如果是字母数字,对吧?因此,不要使用if语句来确定是否要跳过一个字符,而应该使用if语句来确定是否要推送字符。我认为isalnum()
可能就是你想要的。
其次,而不是做strlen()迭代字符串并使用返回值迭代字符串(这两次)尝试:
while('\0' != word[i])
甚至更好:
for(i = 0; '\0' != word[i]; i++)
最后,您对回文的测试可能会稍微加强。在所有情况下循环工作后测试循环值但有点难看。它也不会高兴地受到愚弄。在专业环境中,您会遇到许多人,有些人不那么认真,编辑代码,并且在循环之后使用循环值可能会有风险。也许有一个名为“匹配”的bool并将其初始化为true,然后循环直到堆栈结束或“匹配”变为false并且如果堆栈中的字符“不匹配”则将“匹配”设置为false期望值。这也会更有效率。
当原始问题显然被删除时,我正在撰写这个答案。
如果您希望我发布代码示例,我很乐意这样做,但我想如果我不这样做,您可能会学到更多。如果您想要一个代码示例,或者希望我看一下您在回答之后想出的内容,请随意。
答案 2 :(得分:1)
我只是瞥了一眼......可能会有误解:
while(i<length){
if(isalnum(word[i])) {
temp[n]=word[i];
push(&head, word[i]);
n++;
}
i++;
}
答案 3 :(得分:0)
对于这样的短暂跳跃,重写以消除问题是微不足道的。
while(i<length){
if(isspace(word[i]) || !isalpha(word[i])) {
if(!isdigit(word[i])) {
i++;
continue;
}
}
temp[n]=word[i];
push(&head, word[i]);
i++;
n++;
}