您的位置:首页 > 其它

提取字符串中的数字并分别保存

2008-12-17 09:43 281 查看
在论坛看到一位朋友提的,很简单的东西,就大概写了个,权当顺便复习下字符操作函数。
题目:C++里一个字符串,比如"100,10"或者"100 10",怎么样才能把100和10分别提取出来,保存到2个数组里或者保存到分开的2个字符串里?
这里有两种做法,一种是考虑提取出来的数是否为0开头,如果是0开头则去掉前面的0;另一种是不考虑这个问题。这只是在最后的输出上加不加一个判断和处理的问题。
源程序分别如下:
//(1)去掉数开始的0的
#include<iostream>
#include<string>
#include<vector>
#include<cctype>
using namespace std;

int main()
{
string Str,Str1;
vector<string> S;
cout<<"Input your string:";
getline(cin,Str);
for(string::size_type i=0;i!=Str.size();++i)
{
if(isdigit(Str[i]))
{
Str1.push_back(Str[i]);
}
else if(Str1.size()!=0)
{ S.push_back(Str1);
Str1="";
}
}
if(Str1.size()!=0)
{
S.push_back(Str1);
}
for(vector<string>::size_type j=0;j!=S.size();++j)
{
vector<string>::size_type k=0;
while(k<S[j].size()-1&&S[j][k]=='0')
{
k++;
}
for(;k<S[j].size();++k)
cout<<S[j][k];
cout<<" ";
}
cout<<endl;
return 0;
}

//(2)不考虑数开始的0的
#include<iostream>
#include<string>
#include<vector>
#include<cctype>
using namespace std;

int main()
{
string Str,Str1;
vector<string> S;
cout<<"Input your string:";
getline(cin,Str);
for(int i=0;i!=Str.size();++i)
{
if(isdigit(Str[i]))
{
Str1.push_back(Str[i]);
}
else if(Str1.size()!=0)
{ S.push_back(Str1);
Str1="";
}
}
if(Str1.size()!=0)
{
S.push_back(Str1);
}
for(int j=0;j!=S.size();++j)
cout<<S[j]<<" ";
cout<<endl;
return 0;
}

字符操作函数有时候还真是少不了用,把cctype头文件里的一些贴个在下面再好好看看。
isalnum(c) 如果c是字母或数字,则为true
isalpha(c) 如果c是字母,则为true
iscntrl(c) 如果c是控制字符,则为true
isdigit(c) 如果c是数字,则为true
isgraph(c) 如果c不是空格,但可打印,则为true
islower(c) 如果c是小写字母,则为true
isprint(c) 如果c是可打印的字符,则为true
ispunct(c) 如果c是标点符号,则为true
isspace(c) 如果c是空白字符,则为true
isupper(c) 如果c是大写字母,则为true
isxdigit(c) 如果c是十六进制数,则为true
tolower(c) 如果c是大字字母,则返回其小写字母形式,否则直接返回c
toupper(c) 如果c是小写字母,则返回其大写字母形式,否则直接返回c
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: