【问题标题】:output error when I input a space between my strings当我在字符串之间输入空格时输出错误
【发布时间】:2021-12-30 00:10:18
【问题描述】:

我想编写代码来检查一个字符串在向前或向后读取时是否相同(如回文)。这是我正在使用的代码。

#include <stdio.h>
#include <string.h> 
    
int main(){
    
    int n, right, left;
    char s[101];
    
    scanf("%100d", &n); 
    getchar();
    
    for(int i=0;i<n;i++){
        scanf("%[^\n]", s); 
        getchar();
        left=0; 
        right=strlen(s); 
            
        while((left<=right)&&(s[left]==s[right-1])){ 
            left++; 
            right--;
        }
        
        if(left>right){ 
            printf("True\n"); 
        }else{
            printf("False\n"); 
        }
    }
    
    return 0;
}

如果我输入一个普通的字符串,它工作得很好。例如

输入:

aka
bob
abc

输出:

True
True
False

如果字符串是回文则输出为真,否则输出为假。这工作得很好,但是当我输入一个中间有空格的字符串时,输出不正确。例如

输入:

Taco cat
was it a car or a cat I saw

输出:

False
False

两个字符串都是回文,输出应该是真的,但事实并非如此。我哪里做错了?

【问题讨论】:

    标签: c string


    【解决方案1】:

    这两种失败案例的大小写不同。如果您想不区分大小写,请尝试:

    #include <ctype.h>
    ...
    while((left<=right)&&(tolower(s[left])==tolower(s[right-1]))){
    

    如果您还想忽略空格,则必须在空格上向左或向右前进。我将您的程序简化为只查看一个字符串:

    #include <ctype.h>
    #include <stdio.h>
    #include <string.h>
    
    #define LEN 101
    
    int main() {
        char s[LEN];
        fgets(s, LEN, stdin);
        for(int left = 0, right = strlen(s) - 1; left < right; ) {
            if(isspace(s[left])) {
                left++;
                continue;
            }
            if(isspace(s[right])) {
                right--;
                continue;
            }
            if(tolower(s[left]) != tolower(s[right])) {
                printf("False\n");
                return 0;
            }
            left++;
            right--;
        }
        printf("True\n");
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-05-31
      • 2021-05-04
      • 1970-01-01
      • 1970-01-01
      • 2015-06-04
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多