Getting started with the basics of programming exercises_5
2015-05-27 21:35 星星之火✨🔥 阅读(176) 评论(0) 收藏 举报1、编写函数,把由十六进制数字组成的字符串转换为对应的整型值
编写函数htoi(s),把由十六进制数字组成的字符串(包含可选的前缀0x或0X)转换为与之等价的整型值。字符串中允许包含的数字包括:0~9、a~f 以及 A~F。
#define YES 1 #define NO 0 /* htoi: convert hexadecimal string s to integer */ int htoi(char s[]) { int hexdigit, i, inhex, n; i = 0; if(s[i] == '0') // skip optional 0x or 0X { ++i; if(s[i] == 'x' || s[i] == 'X') ++i; } n = 0; // integer value to be returned inhex = YES; // assume valid hexadecimal digit for( ; inhex == YES; ++i) { if(s[i] >= '0' && s[i] <= '9') hexdigit = s[i] - '0'; else if(s[i] >= 'a' && s[i] <= 'f') hexdigit = s[i] - 'a' + 10; else if(s[i] >= 'A' && s[i] <= 'F') hexdigit = s[i] - 'A' + 10; else inhex = NO; // not a valid hexadecimal digit if(inhex == YES) n = 16 * n + hexdigit; } return n; }
2、编写函数,将字符串s1中任何与字符串s2中字符匹配的字符都删除
/* squeeze: delete each char in s1 which is in s2 */ void squeeze(char s1[], char s2[]) { int i, j, k; for(i = k = 0; s1[i] != '\0'; i++) { for(j = 0; s2[j] != '\0' && s2[j] != s1[i]; j++) ; if(s2[j] == '\0') // end of string - no match s1[k++] = s1[i]; } s1[k] = '\0'; }
3、编写函数, 将字符串s2中的任一字符在字符串s1中第一次出现的位置作为结果返回
编写函数any(s1, s2), 将字符串s2中的任一字符在字符串s1中第一次出现的位置作为结果返回。如果s1中不包含s2中的字符,则返回-1。(标准库函数strpbrk具有同样的功能,但它返回的是指向该位置的指针。)
/* any: return first location in s1 where any char from s2 occurs */ int any(char s1[], char s2[]) { int i, j; for(i = 0; s1[i] != '\0'; i++) for(j = 0; s2[j] != '\0'; j++) if(s1[i] == s2[j]) // match found? return i; // location first match return -1; // otherwise, no match }