我刚刚完成了关于 C 和 Rust元音计数的 CodeWars kata。示例代码简单明了。数组可以用作快速映射。在这里,我将字符映射到逻辑值(0 或 1)。
C实现:
#include <stddef.h>
#include <stdint.h>
// :) This const array design looks smart & IMO-readable. Use of C99 feature.
const uint8_t areVowels[256]= {['a']=1, ['e']=1, ['i']=1, ['o']=1, ['u']=1};
size_t get_count(const unsigned char *s)
{
auto size_t count= 0;
for (;*s!='\0';s++){
count+= areVowels[*s];
}
return count;
}
Run Code Online (Sandbox Code Playgroud)
Rust 实现:
// :( Here is me pain. Unreadable, python3-generated array content.
const ARE_VOWELS:[u8;256]= [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
fn get_count(s: &str) -> usize {
let mut vowels_count: usize …Run Code Online (Sandbox Code Playgroud) ''' Set up '''
s= open("Bilion_of_UTF-8_chars.txt",encoding="UTF-8").read()
'''
The following doesn't look like a cheap operation
because Python3 `str`-s are UTF-8 encoded (EDIT: in some implementations only).
'''
my_char= s[453_452_345]
Run Code Online (Sandbox Code Playgroud)
然而,很多人这样写循环:
for i in range(len(s)):
do_something_with(s[i])
Run Code Online (Sandbox Code Playgroud)
使用索引操作最多n次或更多。
Python3 如何解决这两个代码片段在字符串中索引 UTF-8 字符的问题?
在 Rust 中寻找饱和函数。
这里我称之为fit_to_range(range)。
let input:i64= something;
let saturated:64= input.fit_to_range(7..=4000);
assert!((7..=4000).contains(saturated));
Run Code Online (Sandbox Code Playgroud)