判断字符类型并输出

题目描述

输入一个字符串,含有数字和非数字字符,如“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<iostream>
#include<cstring>
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"<<endl;
    cin>>a;
     sum(a);
     cout<<"the number of the words are "<<x<<endl;
     cout<<"the words are ";
     for(int i=0;i<x;i++)
     cout<<words[i]<<' ';
     cout<<endl;
     cout<<"the number of the  digitals are "<<y<<endl;
     cout<<"the digitals are ";
     for(int i=0;i<y;i++)
     cout<<num[i]<<' ';
     cout<<endl;
     cout<<"the numbers of others are "<<z<<endl;
     cout<<"the others are ";
     for(int i=0;i<z;i++)
    cout<<others[i]<<' ';
    return 0;
 } 

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在C语言中,五种基本数据类型存储空间长度的排列顺序是: A)char B)char=int<=float C)ch...
    夏天再来阅读 3,407评论 0 2
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,771评论 0 33
  • 俞敏洪说过,每个人的一生都该有一段想起来会热泪盈眶的日子。无论身处何处,当你伫立回首,或是不经意间划过回忆的裂隙,...
    黑桃K先森阅读 805评论 0 2
  • 八达公司有一个规定,每年新年和春节期间,都会对公司管理委员会(管委会)进行改选,公司的总经理是通过全体选举...
    王驰1960阅读 616评论 0 1