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; }