4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Rustで全角英数から半角英数へ変換

Last updated at Posted at 2022-10-14

Rustで簡単に全角英数を半角英数に変換する方法をメモ。
charとusizeをうまく変換するのが大切。

Rustで文字1文字を文字コードで表現するには、'\u{xxxx}'のように記述します。
これを知っていれば手軽に変換処理が書けます。

zen2han.rs
/// 全角英数記号を半角英数記号に変換
pub fn zen2han(c: char) -> char {
    match c {
        // half ascii code
        '\u{0020}'..='\u{007E}' => c,
        // FullWidth
        // '!'..='~' = '\u{FF01}'..='\u{FF5E}'
        '\u{FF01}'..='\u{FF5E}' => char_from_u32(c as u32 - 0xFF01 + 0x21, c),
        // space
        '\u{2002}'..='\u{200B}' => ' ',
        '\u{3000}' | '\u{FEFF}' => ' ',
        // others
        _ => c,
    }
}

/// 半角英数記号を全角英数記号に変換
pub fn han2zen(c: char) -> char {
    match c {
        // digit
        '0'..='9' => char_from_u32(c as u32 + 0xFF10 - 0x30, c),
        // alphabet
        'A'..='Z' | 'a'..='z' => char_from_u32(c as u32 + 0xFF21 - 0x41 , c),
        // flag
        '!'..='/' | ':'..='@' | '['..='`' | '{'..='~' => 
            char_from_u32(c as u32 + 0xFF01 - 0x21, c),
        _ => c
    }
}

/// u32からcharに変換
pub fn char_from_u32(i: u32, def: char) -> char {
    char::from_u32(i).unwrap_or(def)
}

上記をテストするコード

test.rs
#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_zen2han() {
        assert_eq!(zen2han('A'), 'A');
        assert_eq!(zen2han('3'), '3');
        assert_eq!(zen2han(' '), ' ');
    }
    #[test]
    fn test_han2zen() {
        assert_eq!(han2zen('A'), 'A');
        assert_eq!(han2zen('3'), '3');
        assert_eq!(han2zen('!'), '!');
    }
}

参考

4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?