我是C语言的初学者,但是我试图制作一个读取输入内容的脚本,并且忽略特殊字符和空格,不管字母是否构成回文,都将输出输入的相反内容。
我试过在fix函数中调整循环的长度,因为我认为这是问题所在,但是据我所知,strlen()可以按预期工作,循环只是在遇到空格时才停止。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX 1000 /* The maximum number of characters in a line of
input
*/
void fix(char str[], char str2[]);
int main()
{
char text[MAX], text2[MAX], text3[MAX], text4[MAX], temp;
int i, j;
int length;
puts("Type some text (then ENTER):");
/* Save typed characters in text[]: */
fgets(text, MAX, stdin);
length = strlen(text) - 1;
strcpy(text2, text);
i = 0;
j = length-1;
while(i < j){
temp = text[i];
text[i] = text[j];
text[j] = temp;
i++;
j--;
}
/* Analyse contents of text[]: */
printf("Your input in reverse is:\n");
printf("%s", text);
fix(text, text3);
printf("%s\n", text3);
fix(text2, text4);
printf("%s\n", text4);
if(strcmp(text4, text3) == 0)
printf("Found a palindrome!\n");
return 0;
}
void fix(char str[], char str2[]){
int i;
for(i = 0; i < strlen(str)-1; i+=1){
if (isalpha(str[i])){
str2[i] = tolower(str[i]);
}
}
}
对于输入“ Nurses,run”,反向字符串正确输出,但是没有“找到回文!”的输出。
打印文本3和4分别打印“ nur”和“ nurses”。
似乎循环在遇到空格时停止,但是我无法弄清为什么会根据完整输入的长度进行循环。
最佳答案
您的fix
函数中存在一个导致未定义行为的问题,因为您仅初始化了结果字符串中的字母字符位置。
因为您的要求是忽略非字母字符,所以需要一个额外的计数器。如果您必须从字符串中删除字符,显然i
会指向错误的字符。因此,您需要计算实际复制到str2
中的字符数。
void fix(char str[], char str2[])
{
int i, copied = 0;
for(i= 0; str[i] != '\0'; i++) // See note 1
{
if (isalpha(str[i])) {
str2[copied++] = tolower(str[i]); // See note 2
}
}
str2[copied] = '\0'; // See note 3
}
笔记:
无需在每个测试中都调用
strlen
。实际上,您根本不需要调用它-这只是测试字符串的null终止符。注意,
copied
在此处递增。这样可以确保如果排除字符,您将不会有空格。您必须记住以空值终止新字符串。
关于c - 消除字符串的特殊字符在空格处停止,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54661657/