Created
January 7, 2022 11:52
-
-
Save tkfmst/c3424a97ade7ca3944b172f150d9c579 to your computer and use it in GitHub Desktop.
rustで3桁区切りなど、文字列に区切り文字を入れる
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![allow(dead_code)] | |
fn add_separator(txt: &str, n: usize, separator: &str) -> String { | |
txt.chars() | |
.rev() | |
.collect::<Vec<char>>() | |
.chunks(n) | |
.map(|cs| cs.iter().collect::<String>()) | |
.collect::<Vec<String>>() | |
.join(separator) | |
.chars() | |
.rev() | |
.collect::<String>() | |
} | |
#[cfg(test)] | |
mod tests { | |
use super::add_separator; | |
#[test] | |
fn add_separator_test() { | |
assert_eq!(add_separator("1234567890", 3, ","), "1,234,567,890"); | |
assert_eq!( | |
add_separator("10110111101111011110110110101100", 8, " "), | |
"10110111 10111101 11101101 10101100" | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment