Replace With Alphabet Position
刚刚做了5道题,发现这题最有意思,前来分享一下,这是一个(6kyu)的题
codewars地址
Instructions
n this kata you are required to, given a string, replace every letter with its position in the alphabet.
If anything in the text isn’t a letter, ignore it and don’t return it.
“a” = 1, “b” = 2, etc.
Example
alphabet_position(“The sunset sets at twelve o’ clock.”)
Should return “20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11” (as a string)
本题就是把字符画串中的字母按照特定方法转化为数字,很显然不区分大小写。有ASCII表可得出这样的结论,无论大小写,只要是字母让其与31进行位与&,就可以得到题目要求数字。
egT->20 t->20
1010100 ->84 110100 ->116
0011111 ->31 001111 ->31
0010100 ->20 0010100 ->20
因为大写与小写只差32,且小写都大于96,大写都小于96,因此T与t区别在与黄色数字,但是结果未变。
My Solution:
#include <stdio.h>
char* alphabet_position(char* text) {
char* string= malloc(strlen(text));//此处动态生成字符串所需内存
string[0]=0;
int i= 0;
for(;*text!='\0';text++)
if(*text> 64)
i+= sprintf(string+i,"%d ",*text&31);//核心代码
//用sprintf()将结果写入string中
string[i-1] = 0;
return string;
}
sprintf()
sprintf函数把结果输出到指定的字符串中。
并且返回字符串的长度
sprintf()用法详解
Sample Tests:
#include <criterion/criterion.h>
#include <string.h>
char *alphabet_position(char *text);
Test(sample_cases, should_pass_all_the_tests_provided) {
char *ptr;
ptr = alphabet_position("The sunset sets at twelve o' clock.");
cr_assert_eq(strcmp(ptr, "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11"), 0);
free(ptr);
ptr = alphabet_position("The narwhal bacons at midnight.");
cr_assert_eq(strcmp(ptr, "20 8 5 14 1 18 23 8 1 12 2 1 3 15 14 19 1 20 13 9 4 14 9 7 8 20"), 0);
free(ptr);
}
Test(number_tests, should_pass) {
srand(time(NULL));
char in[11] = {0};
char *ptr;
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 10; j++) {
char c = rand() % 10;
in[j] = c + '0';
}
ptr = alphabet_position(in);
cr_assert_eq(strcmp(ptr, ""), 0);
free(ptr);
}
}
总结:熟知并善于用一些库函数将会非常省时省力,需要平时多积累,或者多看看一些文档;
还要善于发现数与数之间关系,也就是熟数据结构