注册 登录
编程论坛 C语言论坛

提取字符串中的数字

格物要致知 发布于 2021-08-06 15:59, 1353 次点击
需要从以下字符串中把里面的数字提取出来,字符串为:d:/test/aero-m0.2a0b2.5h3mass0.5
提取出来的结果放到数组中:
[0.2    0    2.5    3     0.5];
尝试了使用sscanf未果,还请高手帮忙指点,谢谢
5 回复
#2
rjsp2021-08-06 16:45
把里面的数字提取出来
是取出 数字字符,比如"0.2",还是数值,比如0.2?
假如出现 "a.5",那提取".5"/0.5,还是 "5"/5 ?
#3
rjsp2021-08-06 17:02
快下班了,估计你也不会回复了。
我根据你说的“尝试了使用sscanf未果”,写了一段只使用 sscanf 的代码,供参考

程序代码:
#include <stdio.h>

void foo( const char* s )
{
    printf( "\"%s\":\n\t", s );
    for( int pos=0; ; )
    {
        int newpos = 0;
        int n = sscanf( s+pos, "%*[^0-9]%n", &newpos );
        if( n == EOF )
            break;
        pos += newpos;

        double val;
        n = sscanf( s+pos, "%lf%n", &val, &newpos );
        if( n == EOF )
            break;
        if( n != 0 )
            pos += newpos;

        printf( " %g", val );
    }
    putchar( '\n' );
}

int main( void )
{
    const char* s = "d:/test/aero-m0.2a0b2.5h3mass0.5";
    foo( s );

    foo( "" );
    foo( "abc" );
    foo( "123" );
    foo( "abc123" );
    foo( "123abc" );

    foo( "abc123def456" );
    foo( "abc123def456ghi" );

    foo( "123abc456def" );
    foo( "123abc456def789" );
}


输出
"d:/test/aero-m0.2a0b2.5h3mass0.5":
         0.2 0 2.5 3 0.5
"":

"abc":

"123":
         123
"abc123":
         123
"123abc":
         123
"abc123def456":
         123 456
"abc123def456ghi":
         123 456
"123abc456def":
         123 456
"123abc456def789":
         123 456 789
#4
格物要致知2021-08-06 17:16
回复 2楼 rjsp
是需要float格式,不是字符格式
#5
格物要致知2021-08-06 17:24
回复 3楼 rjsp
太给力了,谢谢
#6
ladin2021-08-16 13:26
1