Guest User

Untitled

a guest
Jan 18th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. fn replace_at_idx_in_each_word(line: &str, delims: &[char], idx: usize, replace: char) -> String {
  2. let mut res = String::with_capacity(line.len());
  3.  
  4. for (word, delim) in WordsBy::new(line, delims) {
  5. replace_nth_and_append(&mut res, word, idx, replace);
  6. res.extend(delim);
  7. }
  8.  
  9. res
  10. }
  11.  
  12. fn replace_nth_in_each_word(line: &str, delims: &[char], pos: usize, replace: char) -> String {
  13. assert!(pos != 0, "can not replace zeroth character in word");
  14. replace_at_idx_in_each_word(line, delims, pos - 1, replace)
  15. }
  16.  
  17. struct WordsBy<'a> {
  18. line: Option<&'a str>,
  19. delims: &'a [char],
  20. }
  21.  
  22. impl<'a> WordsBy<'a> {
  23. fn new(line: &'a str, delims: &'a [char]) -> Self {
  24. Self {
  25. line: Some(line),
  26. delims,
  27. }
  28. }
  29. }
  30.  
  31. impl<'a> Iterator for WordsBy<'a> {
  32. type Item = (&'a str, Option<char>);
  33.  
  34. fn next(&mut self) -> Option<Self::Item> {
  35. let line = self.line.take()?;
  36. if let Some((pos, delim)) = line.char_indices().find(|(_, c)| self.delims.contains(&c)) {
  37. let (word, rest) = line.split_at(pos);
  38. let rest = &rest[delim.len_utf8()..];
  39. if !rest.is_empty() {
  40. self.line = Some(rest)
  41. }
  42.  
  43. Some((word, Some(delim)))
  44. } else {
  45. Some((line, None))
  46. }
  47. }
  48. }
  49.  
  50. fn replace_nth_and_append(acc: &mut String, word: &str, idx: usize, new: char) {
  51. if let Some((pos, old)) = word.char_indices().nth(idx) {
  52. let (before, after) = word.split_at(pos);
  53. acc.push_str(before);
  54. acc.push(new);
  55. acc.push_str(&after[old.len_utf8()..])
  56. } else {
  57. acc.push_str(word)
  58. }
  59. }
  60.  
  61. fn main() {
  62. let line = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
  63. let delims = [' '];
  64. let result = replace_nth_in_each_word(line, &delims, 2, '%');
  65. assert_eq!(
  66. result,
  67. "L%rem i%sum d%lor s%t a%et, c%nsectetur a%ipiscing e%it."
  68. );
  69. }
Add Comment
Please, Sign In to add comment