从零开始codewar——C语言(第一战)

本文介绍了一个简单的C语言函数,该函数能够从输入的字符串中提取所有数字字符,并将其转换为整数。例如,输入字符串hell5owor6ld将返回56。此函数通过遍历字符串并检查每个字符是否为数字来工作。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值