在句子中获取单词的第一个字母

时间:2018-05-14 12:15:20

标签: string rust iterator text-manipulation

如何从句子中获得第一个字母;示例:“Rust是一种快速可靠的编程语言”应返回输出riafrpl

fn main() {
    let string: &'static str = "Rust is a fast reliable programming language";
    println!("First letters: {}", string);
}

2 个答案:

答案 0 :(得分:9)

double first = 0.0;
double second= 0.0;
int lines = 0;

if (scanner.hasNextLine()) {
    String line = scanner.nextLine();
    String[] numbers = line.split("\\s+"); // split on white spaces
    first += Double.parseDouble(numbers[0]);
    second += Double.parseDouble(numbers[1]);
    lines++;
}
if (lines > 0) {
    System.out.println(first / lines);
    System.out.println(second / lines);
}

答案 1 :(得分:5)

这对Rust的迭代器来说是一个完美的任务;这是我将如何做到的:

fn main() {                                                                 
    let string: &'static str = "Rust is a fast reliable programming language";

    let first_letters = string
        .split_whitespace() // split string into words
        .map(|word| word // map every word with the following:
            .chars() // split it into separate characters
            .next() // pick the first character
            .unwrap() // take the character out of the Option wrap
        )
        .collect::<String>(); // collect the characters into a string

    println!("First letters: {}", first_letters); // First letters: Riafrpl
}