[8 kyu]
[2017-03-11]
[
description:
Write a function which removes from string all non-digit characters and parse the remaining to number. E.g: "hell5o wor6ld" -> 56
code:
/* Adapted from the test cases originally written by a code warrior wichu */
#include <criterion/criterion.h>
int get_number_from_string(const char *src);
Test(CoreTests, ShouldPassAllTheTestsProvided) {
cr_assert_eq(get_number_from_string("1"), 1);
cr_assert_eq(get_number_from_string("123"), 123);
cr_assert_eq(get_number_from_string("this is number: 7"), 7);
cr_assert_eq(get_number_from_string("$100 000 000"), 100000000);
cr_assert_eq(get_number_from_string("hell5o wor6ld"), 56);
cr_assert_eq(get_number_from_string("one1 two2 three3 four4 five5"), 12345);
}
int get_number_from_string(const char *src)
{
int res = 0;
while ( *src )
{
if ( *src >= '0' && *src <= '9' )
res = res*10 + (*src - '0');
src++;
}
return res;
}
]
本文介绍了一个简单的C语言函数,该函数能够从输入的字符串中提取所有数字字符,并将其转换为整数。例如,输入字符串hell5owor6ld将返回56。此函数通过遍历字符串并检查每个字符是否为数字来工作。
252

被折叠的 条评论
为什么被折叠?



