Posted on 2009-09-08 11:28
天之驕子 閱讀(12509)
評論(1) 編輯 收藏 引用
下面程序將字符串中的連續數字提取出來,并存放到一維數組中。比如說一個字符串:"a284twx234 je3432",把“284“,“234”,“3432”這3個連續數字提取出來,分別存放到a[0],a[1].a[2]中。
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main()


{
char str[] = "a284twx234 je3432";
int len=strlen(str);
char buf[100];
int a[3];
int i = 0;
while ( str[i] != '\0' )

{
if (isdigit(str[i]))
buf[i] = str[i];
else buf[i] = ' ';
++i;
}
buf[i] = '\0';
sscanf (buf,"%d %d %d", &a[0], &a[1], &a[2]);
printf ("%d %d %d\n", a[0], a[1], a[2]);
return 0;
}


/**/////////////////////////////////////////
//實現了把一個字符串中的第一次出現的有效數字
//提取出來比如:abge_+*123.456dfsdf
//程序運行的結果應該是:123.456

/**////////////////////////////////////////
#include<iostream>
#include<cstring>
#include<cstdio>

#define MAXLEN 50 //定義字符數組的上屆
using namespace std;

int main()


{
char numstr[MAXLEN] = "#define MAX_MODE 20 //方式個數";
int flag=1,i=0,j=0,h=0;
double m=0,sum=0,n=0;
//cout<<"輸入一個字符串:";
//cin>>numstr;

cout<<numstr;

// 1.剔除+-或者0~9前面的非法字符;
for(;i<strlen(numstr);i++)

{
if((numstr[i]<='9' && numstr[i]>='0')
|| numstr[i]=='+' || numstr[i]=='-')
break;
else
j++;
}
if(numstr[j]=='-') //判斷負號,為最后的輸出做準備
flag=-1;
if(numstr[j]=='+' || numstr[j]=='-') //讓j指向第一個數字元素(剔除+-號)
j++;
i=j; //讓i也指向第一個數字元素

//2.剔除數字元素后面的非法字符;
h=j;
for(;i<strlen(numstr);i++)

{
if( (numstr[i]<='9' && numstr[i]>='0')
||numstr[i]=='.')
h++;
else
break;
}
h-=1;

//3.計算整數 部分
for( ; numstr[j]!='.' && j<=h; j++) //整數部分計算的實現

{
n=n*10+numstr[j]-'0';
}

//4.計算小數部分
if(j<h && numstr[h]!='.')

{
for(j++;j<=h;h--) //讓j指向第一個數字字符,從最后一個字符元素往前算

{ //小數部分,直到h=j時停止。
m=m*0.1+numstr[h]-'0';
}
m*=0.1;
}
//5.合成數字
sum=n+m;
sum=sum*flag;
cout<<"輸出轉換字符結果:";
cout<<sum<<endl;
printf("printf輸出的結果是: %lf",sum);

return 0;
}
//將string類對象中的數字字符提取出來
int CFileIndexDialog::string2int(CString str)


{
int length;
int i;
TCHAR temp2[15];
lstrcpy(temp2,str); //copies a string to a buffer

TCHAR temp[4];
int count;
count=0;
length=strlen(temp2); //length保存了字符數組temp2的長度
for(i=0;i<length;i++)

{
if ((temp2[i]<='9')&&(temp2[i]>='0'))

{
temp[count]=temp2[i];
count++;
}
}
return (::atoi(temp));
}