繁体   English   中英

检查字符串中的字符是字母,数字还是特殊字符。 在C

[英]checking if the characters in a string are either alphabets, numbers, or special characters. in c

我一直在研究一个问题,要求检查字符串中的数字,字母或其他特殊字符。

例如,如果您有两个输入。 一个是整数,它是字符串长度,第二个输入是字符串。

input1: 6
input2: 4!hs%5.

输出应为: noaaon

n代表数字,a代表字母,o代表其他。

#include<stdio.h>
#include<string.h>

int main(){
    char c[20];
    int n,i;

    scanf("%d %s",&n,c);
    for(i=1;c[i]<=n;i++)
        if(i>='a' && i<='z')
            printf("%c\n",(c[i]));
    if(i=='!')
        printf("%c \n",i);
    else
    {
        printf("%c \n",);
    } 
    return 0;
}

为什么不尝试像isalpha()isdigit()这样更简单的东西

for( i = 0 ; i < n ; i++ )
  {
     if ( isalpha( c[i] ) )
        // it is an alphabet, so some code
     else if ( isdigit ( c[i] ) )
        // it is a number , so some code
     else
        // it is some other character
  }

这实际上比您当前的代码简单得多

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(void) {
    char input[10];
    char out[10];
    int i;
    memset(out, '\0', 10);
    scanf("%s", input);
    for(i = 0; i < strlen(input); ++i){
        if( (c[i] >= 'a' && c[i] <= 'z') ||  (c[i] >= 'A' && c[i] <= 'Z') ){
            out[i] = 'a';
        }
        else if(isdigit(c[i])){
            out[i] = 'n';
        }
        else{
            out[i] = 'o';
        }
    }
    printf("%s", out);
    return 0;
}

您可以在这里尝试: http : //ideone.com/d8Id1Z

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM