1. 程式人生 > >從零開始codewar——C語言(第一戰)

從零開始codewar——C語言(第一戰)

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