Replace With Alphabet Position(codewars)

本文介绍了一个有趣的编程挑战,即如何将字符串中的每个字母转换为其在字母表中的位置,并忽略所有非字母字符。通过使用ASCII码与31进行位与运算,可以轻松实现这一转换,而不会受到大小写的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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); 
    }
}

总结:熟知并善于用一些库函数将会非常省时省力,需要平时多积累,或者多看看一些文档;
还要善于发现数与数之间关系,也就是熟数据结构

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值