How to change order of letters in every word beside first and last letter in sentence in RUST? [duplicate]

让人想犯罪 __ 提交于 2021-01-29 08:44:14

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!