๊ด€๋ฆฌ ๋ฉ”๋‰ด

IT’s Portfolio

[Rust] Start Rust (Day 16) - Rust Example Script 4 [Pig Latin] ๋ณธ๋ฌธ

Development Study/Rust

[Rust] Start Rust (Day 16) - Rust Example Script 4 [Pig Latin]

f1r3_r41n 2023. 2. 25. 14:18
728x90
๋ฐ˜์‘ํ˜•

๐Ÿฆ€ Rust Day 16

๐Ÿณ๏ธ Rust Example Script 4 - Pig Latin

1๏ธโƒฃ Description

  • ๋ฌธ์ž์—ด์„ ํ”ผ๊ทธ ๋ผํ‹ด(Pig Latin) ์œผ๋กœ ๋ฐ”๊พธ๋Š” ํ”„๋กœ๊ทธ๋žจ ์ž‘์„ฑ
  • ํ”ผ๊ทธ ๋ผํ‹ด(Pig Latin)
    • ๋‹จ์–ด๊ฐ€ ์ž์Œ์œผ๋กœ ์‹œ์ž‘ํ•  ๊ฒฝ์šฐ ํ•ด๋‹น ์ž์Œ์„ ๋‹จ์–ด์˜ ๋์œผ๋กœ ์ด๋™ํ•˜๊ณ  "ay" ๋ฅผ ๋ง๋ถ™์ž„
      • first -> irst-fay
    • ๋ชจ์Œ์œผ๋กœ ์‹œ์ž‘ํ•  ๊ฒฝ์šฐ ๋‹จ์ˆœํžˆ ๋์— "hay" ๋ฅผ ๋ง๋ถ™์ž„
      • apple -> apple-hay

2๏ธโƒฃ how it works

  • ์˜์–ด ๋‹จ์–ด ๋ฌธ์ž์—ด ์ž…๋ ฅ๋ฐ›๊ธฐ
  • ๋ฌธ์ž์—ด์˜ ์กฐ๊ฑด์— ๋งž๊ฒŒ ๊ฒฐ๊ณผ ์ถœ๋ ฅ

3๏ธโƒฃ Code

// src/main.rs
use std::io;

// ๋ชจ์Œ์— ๋Œ€ํ•œ ์ƒ์ˆ˜ VOWEL ์„ ์–ธ
const VOWEL: [char; 5] = ['a', 'e', 'i', 'o', 'u'];

fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).
        expect("No input!");

    println!(
        "{}",
        // ๋ฐ˜ํ™˜๋ฐ›์€ bool๋กœ ๊ฐ ์ƒํ™ฉ์— ๋”ฐ๋ผ ์ถœ๋ ฅํ•˜๋Š” match ํ‘œํ˜„์‹
        match compare(&input) {
            false => {
                format!("{}-{}ay", 
                String::from(&input.trim()[1..]), &input[..1])
            },
            true => {
                format!("{}-hay", 
                input.trim())
            },
        }
    );
}

// ๋ฌธ์ž์—ด์˜ ์ฒซ ๋ฒˆ์งธ ์ž๋ฆฌ๊ฐ€ ์ž์Œ์ธ์ง€ ๋ชจ์Œ์ธ์ง€ ์ƒ์ˆ˜์™€ ๋น„๊ตํ•˜๋Š” ํ•จ์ˆ˜
fn compare(msg: &String) -> bool {
    // ๋ณ€์ˆ˜ f_word๋Š” ๋ฌธ์ž์—ด ์Šฌ๋ผ์ด์‹ฑ์„ ์‚ฌ์šฉํ•ด &str ํƒ€์ž…
    let f_word = &msg[..1];
    let mut dis = false;

    for c in &VOWEL {
        // ๋ณ€์ˆ˜ c๋Š” &char ํƒ€์ž…์ด๊ธฐ์— to_string() ๋ฉ”์„œ๋“œ๋กœ ํƒ€์ž… ๋ณ€๊ฒฝ์ด ํ•„์š”ํ•จ
        if c.to_string() == f_word {
            dis = true;
            break;
        }
    }

    dis
}

4๏ธโƒฃ Result

  • first
      first // input
      irst-fay // output
  • apple
      apple // input
      apple-hay // output
  • Rust
      Rust // input
      ust-Ray // output
728x90
๋ฐ˜์‘ํ˜•
Comments