问题
I need to change order of letter in every word of sentence besides first and last letter (example:"According, researcher" => "Accroidng, rseaecrehr" or "University, it doesn't matter" => "Uinevsrtiy, it deosn't mtaetr"). I have constant of separators to split my string on words. Semicolon, comma or other separator must be saved.
const SEPARATORS: &str = " ,;:!?./%*$=+)@_-('\"&1234567890\r\n";
Someone know how to do this ?
回答1:
This is tricky since strings are encoded in UTF8 format, you can't just shuffle the bits. Here's what I came up with:
// Random stuff for shuffling the letters
use rand::thread_rng;
use rand::seq::SliceRandom;
// Regex to simplify finding words
use regex::Regex;
fn main() {
let test = "University, it doesn't matter";
// If you need a specific subset, you could change the Regex
// I'm just grabbing consecutive alphabetic characters which should accomplish the same thing
let re = Regex::new("[[:alpha:]]+").unwrap();
let mut rng = thread_rng();
// First change our &str into a mutable Vec<char>
let mut char_array: Vec<char> = test.chars().collect();
// Then use the regex to iterate through each "word" found
re.find_iter(test).for_each(|m| {
// Carefully reduce the size of the "word" by one on each side
let mut range = m.range();
if range.start + 1 < range.end {
range.start += 1
}
if range.end - 1 >= range.start {
range.end -= 1
}
// Shuffle the portion of the character array that represents the inner letters of the "word"
char_array[range].shuffle(&mut rng);
});
// Finally we put it all back into a string
let r: String = char_array.iter().collect();
// TADA!!
println!("{}", r);
}
来源:https://stackoverflow.com/questions/61666177/how-to-change-order-of-letters-in-every-word-beside-first-and-last-letter-in-sen