首页 > 解决方案 > 如何过滤掉 ASCII 中“Z”和“a”之间的垃圾?

问题描述

#include <stdio.h>

void main()
{
    char ch;

    clrscr();
    ch = 'A';
    while(ch <= 'z')
    {
       printf("%c", ch);
       ch++;
    }
    getch();
 }  

如何从该程序的输出中删除诸如[, ], ',等的垃圾?\

标签: cwhile-loopascii

解决方案


就像评论中提到的那样跳过 Z 之间的所有内容,例如:

#include "stdio.h"
int main(){
    char ch = 'A';
    while(ch <= 'z'){
        if(ch <= 'Z' || ch >= 'a'){
            printf("%c", ch);
        } 
        ch++;
    } 
    printf("\n");
    return 0;
}

或者使用for循环,因为您知道值范围的开始和结束:

#include "stdio.h"
int main(){
    char ch;
    for(ch = 'A'; ch <= 'z'; ch++){
        // loop through range of ASCII values from 'A' to 'z', upper case
        // and lower case letters, and print out only alphabetic characters.
        if(ch <= 'Z' || ch >= 'a'){
            // character is in range of 'A' thru 'Z' or 'a' thru 'z'.
            printf("%c", ch);
        } 
    } 
    printf("\n");
    return 0;
}

或者使用该isalpha()函数来检测字符是否为字母。

#include "stdio.h"

int main() {
    char ch;
    // loop through range of ASCII values from 'A' to 'z', upper case
    // and lower case letters, and print out only alphabetic characters.
    for (ch = 'A'; ch <= 'z'; ch++)  isalpha (ch) && printf ("%c", ch);
    printf("\n");
    return 0;
}

推荐阅读