判断字符类型并输出

题目描述

输入一个字符串,含有数字和非数字字符,如“sum=abc+234; while(abc<=700)tab{ass=346++;bss=abc+267;}”,将其中连续的数字作为一个整数,依次存放到一个数组nums中;连续的字母作为一个单词存放到一个数组words中;其它所有字符存放到一个数组others中。例如,234放在nums[0],700放在nums[1]……,sum放在words[0],abc放在words[1]……,=放在others[0],+放在others[1]……。在主函数中分别输出各自的统计结果。结合指针完成该题。

题目分析

由于连续的数字和字符是要合在一起的,一开始考虑使用二维数组。
发现如果是f(int a[ ][ ])编译其报错,我推测,应该是a[ ][ ]不代表任何东西,如果是二维数组中的a[0]就可以,因为此时代表的是一个地址。
所以,就改变策略,考虑用字符串。因为字符串尾端添加字符很方便,用加号即可。
在写的过程中,还要注意,i,x,y,z的自增位置,以及各种判断条件。由于我编写的程序中有一个if特别长,所以要格外注意括号以及&&和||
最后,注意,在判断others时,不仅要考虑不是数字和字母还要考虑是否为'\0'

#include
#include
using namespace std;
string num[100],words[100];
char others[100];
int x,y,z;
void sum(char a[])
{
     x=0;
    char *p=a;
    int i=0;
    while(*(p+i)!='\0')
    {
        while((*(p+i)>='a'&&*(p+i)<='z')||(*(p+i)>='A'&&*(p+i)<='Z'))
        {
            words[x]+=*(p+i);//统计字符串 
            i++;
            if(!((*(p+i)>='a'&&*(p+i)<='z')||(*(p+i)>='A'&&*(p+i)<='Z')))
            {
                x++;
                break;
            }
        }
        while(*(p+i)>='0'&&*(p+i)<='9')
        {
            num[y]+=*(p+i);//统计数字
            i++; 
            if(!(*(p+i)>='0'&&*(p+i)<='9'))
            {
                y++;
                break;
            }
        }
        while(!(((*(p+i)>='a'&&*(p+i)<='z')||(*(p+i)>='A'&&*(p+i)<='Z'))||(*(p+i)>='0'&&*(p+i)<='9')||*(p+i)=='\0'))
        {
            others[z]=*(p+i);
            z++;
            i++;
        }
    }
}
int main()
{
    char a[100];
    cout<<"please input a string"<>a;
     sum(a);
     cout<<"the number of the words are "<

如果有更好的方法欢迎提出哟

你可能感兴趣的:(判断字符类型并输出)