Skip to content

Instantly share code, notes, and snippets.

@tkfmst
Created January 7, 2022 11:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tkfmst/c3424a97ade7ca3944b172f150d9c579 to your computer and use it in GitHub Desktop.
Save tkfmst/c3424a97ade7ca3944b172f150d9c579 to your computer and use it in GitHub Desktop.
rustで3桁区切りなど、文字列に区切り文字を入れる
#![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