字符串指针相关习题

1.统计带数字的字符串中的数字个数,并且输出数字。

#include <iostream>
using namespace std;
int cton(char* s,int *num){
    int m,n=0;
    while (char c = *s++){
        if (c>='0'&&c<='9'){
            m  = c-'0';
            while ((c=*s++)&&c>='0'&&c<='9'){
                m = m*10 + c -'0';
            }
            num[n++] = m;
        }
    }
    return n;
}
int main(){
    char s[200];
    int num[20];
    cin.getline(s,200);
    int total = cton(s,num);
    cout<<"共有"<<total<<"个数字"<<endl;
    for (int i=0;i<total;i++){
        cout<<num[i]<<endl;
    }
    return 0;
}


2.字符串的复制,拼接和逆序输出

#include <iostream>
using namespace std;
//字符串复制函数
char *stringcopy(char *to,char* from){
    char *p=to;
    while(*to++=*from++);
    return p;
}
//字符串拼接函数
char *stringcat (char *to,char* from ){
    char *p = to;
    while(*to++);
    to--;
    while(*to++=*from++);
    return p;
}
//字符串逆序输出
char *charInverse(char *ptr){
    char *p1,*p2,temp;
    p1=p2=ptr;
    while (*p2++);
    p2-=2;
    while(p1<p2){
        temp = *p2;
        *p2--=*p1;
        *p1++=temp;
    }
    return ptr;
}
int main(){
    /*字符串复制*/
    char copy1[]="copyBase",copy2[]="copyWorld";
    cout<<stringcopy(copy2,copy1)<<endl;
    /*字符串拼接*/
    char to[]="hello,";char from[]="world!";
    cout<<stringcat (to,from)<<endl;
    /*字符串逆序输出-函数法*/
    char verBase[]="NanjingUniversityOfPostAndTelecommunications";
    cout<<verBase<<endl;
    cout<<charInverse(verBase)<<endl;
    /*字符串逆序输出-一般输出法*/
    //先统计字符串长度
    char s[100];
    cin.getline(s,100);
    int i=0;
    while(s[i]) i++;
    cout<<"字符串长度为"<<i<<endl;
    //倒序输出字符串
    for (char *p=s+i-1;p>=s;p--) cout<<*p;

    return 0;
}

3.统计字符串中的字符个数,并输出余串

#include <iostream>
using namespace std;

int strfind(char * &p1,char ch){
    int num=0;
    char *p;
    while(*p1++){
        if(*p1==ch){
            num++;
            p=p1;
        }
    }
    p1=p;
    return num;
}
int main(){
    char s1[50];
    char ch;
    char *p1=s1;
    cout<<"请输入一个字符串"<<endl;
    cin.getline(p1,50);
    cout<<"请输入要查找的字符"<<endl;
    cin>>ch;
    cout<<"共有"<<strfind(p1,ch)<<"个字符"<<endl;
    cout<<"余下子串为:"<<p1<<endl;


    return 0;
}












  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值