从字符串中取出素数

来源:互联网 发布:淘宝发货地址不一样 编辑:程序博客网 时间:2024/05/16 04:33
/*试建立一个类 Str,把一个字符串中连续的数字字符看成一个整数,若该数是一个素数,则对其求和。如 char s[]=“1ad34be5c67dw11egg77fuy5”中,这样的整数有 1、34、5、67、11、77、5,其中素数有 5、67、11、5,其和为 5+67+11+5=88。请编写程序,实现这样的运算。具体要求如下:(1)私有数据成员    char s[100]; 存放需要处理的字符串。    int b[20]; 存放分离出的整数。    int ss;存放素数之和。    int count; 分离出整数的个数(2)公有成员函数    Str(char *p=0);构造函数,为 s 数组、私有数据成员 ss、count置0.    int pre(int n);测试 n 为素数。    void SUM(); 分离字符串中连续的数字为整数,并求出素数和。    void show(); 输出字符串、分离出整数和素数之和。(3)在主函数中完成对该类的测试。输入一个字符串到字符数组 str 中,定义一个 Str 类的对象 test,用 str 初始化对象 test,调用成员函数完成运算。*/#include<iostream>using namespace std;class Str{private:    char s[100];    int b[20];    int ss;    int count;public:    Str(char *);    int pre(int);    void SUM();    void show();};Str::Str(char *p = 0){    int xunhuan_bianliang = 0;    while (*p)    {        s[xunhuan_bianliang] = *p;        p++;        xunhuan_bianliang++;    }    s[xunhuan_bianliang] = '\0';    ss = 0;    count = 0;}int Str::pre(int n){    if (n == 1 || n == 0)        return 0;    for (int i = 2; i < n; i++)    {        if (n%i == 0)            return 0;    }    return 1;}void Str::SUM(){    char *temp1 = s;    while (*temp1)    {        ss = 0;  //尤其重要,要不然出错        char *temp2 = temp1;        while (*temp2 <= '9'&&*temp2 >= '0')        {            temp2++;        }        //把数字字符串赋值给数组        char *ptr = temp1;  //这里要尤其注意,给后面留路子        while (ptr != temp2)        {            ss *= 10;            ss += (*ptr - '0');            ptr++;        }        if (this->pre(ss))        {            b[count] = ss;            count++;            ss = 0;        }        //防止多位数        if (temp1 == temp2)            temp1++;        else            temp1 = temp2;    }}void Str::show(){    cout << "字符串为:" << s << endl;    cout << "分离出的整数为:";    for (int i = 0; i < count; i++)    {        cout << b[i] << '\t';    }}int main(){    char aa[] = "1ad34be5c67dw11egg77fuy5";    Str str(aa);    str.SUM();    str.show();    system("pause");    return 0;}
原创粉丝点击