Rust字符串处理

// use std::collections::HashMap;
// use std::fmt::Formatter;

fn main() {
    f();
}

fn f() {
    assert_eq!('4'.is_numeric(), true);
    assert_eq!('q'.is_alphabetic(), true);
    assert_eq!('x'.is_alphanumeric(), true);
    assert_eq!(' '.is_whitespace(), true);
    assert_eq!('\u{85}'.is_control(), true);
    assert_eq!('a'.to_digit(16), Some(10));
    assert_eq!(std::char::from_digit(15, 16), Some('f'));
    assert_eq!(char::is_digit('f', 16), true);
    assert_eq!('f'.is_uppercase(), false);
    assert_eq!('f'.is_lowercase(), true);
    assert_eq!('s'.to_uppercase().next(), Some('S'));
    assert_eq!('B' as u32, 66);

    assert_eq!(char::from(66), 'B');
    assert_eq!(std::char::from_u32(0x9942), Some('饂'));

    // Unicode的大小写转换不一定是一对一过程
    let mut x = 'ß'.to_uppercase();
    assert_eq!(x.next(), Some('S'));
    assert_eq!(x.next(), Some('S'));
    assert_eq!(x.next(), None);

    let x: &str = "bookkeeping";
    assert_eq!(&x[..4], "book");
    assert_eq!(&x[5..], "eeping");
    assert_eq!(&x[2..4], "ok");
    assert_eq!(x[..].len(), 11);
    assert_eq!(x[5..].contains("boo"), false);
    assert_eq!(x[0..0].len(), 0);
    assert_eq!(x[0..1].len(), 1);
    assert_eq!(x[0..0].is_empty(), true);
    assert_eq!(x[5..].split_at(2), ("ee", "ping"));

    let x: &str = "Rust (饂)";
    assert_eq!(x[6..].chars().next(), Some('饂'));
    assert_eq!(x[..].is_char_boundary(8), false);

    let mut x: String = "Zero".to_string();
    x.push('A');
    assert_eq!(x, "ZeroA");

    let alpha: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    let mut x: String = "=>".to_string();
    x.push_str(&alpha[3..4]);
    assert_eq!(x, "=>D");

    let mut x = "con".to_string();
    x.extend("tri but ion".split_whitespace());
    assert_eq!(x, "contribution");

    use std::fmt::Write;
    let mut x: String = String::new();
    write!(x, "Succeed to {}", "open file").unwrap();
    assert_eq!(x, "Succeed to open file");

    let left: String = "x".to_string();
    let mut right: String = "y".to_string();
    assert_eq!(left + " and " + &right, "x and y");

    right += " is ok";
    assert_eq!(right, "y is ok");
    right.clear();
    assert_eq!(right, "");

    let mut x: String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".to_string();
    x.truncate(3);
    assert_eq!(x, "ABC");

    let mut x: String = "ABC".to_string();
    assert_eq!(x.pop(), Some('C'));

    let mut x: String = "ABC".to_string();
    assert_eq!(x.remove(1), 'B');
    assert_eq!(x.len(), 2);

    let mut x: String = "chocolate".to_string();
    assert_eq!(x.drain(3..6).collect::<String>(), "col");
    assert_eq!(x, "choate");

    let mut x: String = "chocolate".to_string();
    x.drain(3..6);
    assert_eq!(x, "choate");

    let x: &str = "One fine day, in the middle of the night";
    assert_eq!(x.find(','), Some(12));
    assert_eq!(x.find("night"), Some(35));
    assert_eq!(x.find(char::is_whitespace), Some(3));
    assert_eq!(
        "## Elephants".trim_start_matches(|ch: char| { ch == '#' || ch.is_whitespace() }),
        "Elephants"
    );

    let x: &str = "\t    function noodle() { ";
    assert_eq!(
        x.trim_start_matches(&[' ', '\t'] as &[char]),
        "function noodle() { "
    );

    assert_eq!(
        "We also know there are known unknowns".find("know"),
        Some(8)
    );
    assert_eq!(
        "We also know there are known unknowns".rfind("know"),
        Some(31)
    );
    assert_eq!(
        "We also know there are known unknowns".find("ya know"),
        None
    );
    assert_eq!(
        "We also know there are known unknowns".rfind(char::is_uppercase),
        Some(0)
    );
    assert_eq!(
        "The only thing we have to fear is fear itself".replace("fear", "spin"),
        "The only thing we have to spin is spin itself"
    );
    assert_eq!(
        "`Borrow` and `BorrowMut`".replace(|ch: char| { !ch.is_alphanumeric() }, "?"),
        "?Borrow??and??BorrowMut?"
    );
    assert_eq!(
        "élan".char_indices().collect::<Vec<_>>(),
        vec![(0, 'é'), (2, 'l'), (3, 'a'), (4, 'n')]
    );

    assert_eq!(
        "élan".bytes().collect::<Vec<_>>(),
        vec![195, 169, b'l', b'a', b'n']
    );

    assert_eq!(
        "jimb:1000:Jim Blandy:".split(':').collect::<Vec<_>>(),
        vec!["jimb", "1000", "Jim Blandy", ""]
    );

    assert_eq!(
        "127.0.0.1 localhost\n\
         127.0.0.1 www.redis.com\n"
            .split_terminator('\n')
            .collect::<Vec<_>>(),
        vec!["127.0.0.1 localhost", "127.0.0.1 www.redis.com"]
    );

    assert_eq!(
        "This is just to say\n\
         I have eaten\n\
         the plums\n\
         again\n"
            .split_whitespace()
            .collect::<Vec<_>>(),
        vec!["This", "is", "just", "to", "say", "I", "have", "eaten", "the", "plums", "again"]
    );

    assert_eq!("\t*.rs     ".trim(), "*.rs");
    assert_eq!("\t*.rs     ".trim_start(), "*.rs     ");
    assert_eq!("\t*.rs     ".trim_end(), "\t*.rs");
    assert_eq!("001990".trim_start_matches('0'), "1990");

    use std::str::FromStr;
    assert_eq!(usize::from_str("3628800"), Ok(3628800));
    assert_eq!(f64::from_str("not a float at all").is_err(), true);

    assert_eq!(
        std::net::IpAddr::from_str("2408:820c:8218:b580:186b:9e8c:2a7:bd76").unwrap(),
        std::net::IpAddr::from([0x2408, 0x820c, 0x8218, 0xb580, 0x186b, 0x9e8c, 0x2a7, 0xbd76])
    );
    assert_eq!(
        "2408:820c:8218:b580:186b:9e8c:2a7:bd76"
            .parse::<std::net::IpAddr>()
            .unwrap(),
        std::net::IpAddr::from([0x2408, 0x820c, 0x8218, 0xb580, 0x186b, 0x9e8c, 0x2a7, 0xbd76])
    );

    assert_eq!(format!("{}x", "y"), "yx");
    assert_eq!(format!("{}", true), "true");
    assert_eq!(format!("{:.3}", f64::sqrt(3.0) / 2.0), "0.866");

    assert_eq!(
        format!(
            "{}",
            std::net::IpAddr::from([0x2408, 0x820c, 0x8218, 0xb580, 0x186b, 0x9e8c, 0x2a7, 0xbd76])
        ),
        "2408:820c:8218:b580:186b:9e8c:2a7:bd76"
    );

    assert_eq!(
        std::net::IpAddr::from([0x2408, 0x820c, 0x8218, 0xb580, 0x186b, 0x9e8c, 0x2a7, 0xbd76])
            .to_string(),
        "2408:820c:8218:b580:186b:9e8c:2a7:bd76"
    );

    assert_eq!(
        format!(
            "{:?}",
            vec![
                std::net::IpAddr::from([
                    0x2408, 0x820c, 0x8218, 0xb580, 0x186b, 0x9e8c, 0x2a7, 0xbd76
                ]),
                std::net::IpAddr::from_str("192.168.0.1").unwrap(),
            ]
        ),
        "[2408:820c:8218:b580:186b:9e8c:2a7:bd76, 192.168.0.1]"
    );

    assert_eq!(
        String::from_utf8(vec![0xe9, 0x8c, 0x86]).ok(),
        Some("錆".to_string())
    );

    assert_eq!(
        String::from_utf8(vec![0x9f, 0xf0, 0xa6, 0x80]).is_err(),
        true
    );
    assert_eq!(
        String::from_utf8(vec![0x9f, 0xf0, 0xa6, 0x80])
            .unwrap_err()
            .into_bytes(),
        vec![0x9f, 0xf0, 0xa6, 0x80]
    );

    // 自定义的用户名
    assert_eq!(get_name(), "feihu");

    assert_eq!(
        format!(
            "{}",
            Complex64 {
                re: -0.5,
                im: 0.866,
            }
        ),
        "-0.5 + 0.866i"
    );

    let mut x: std::collections::HashMap<&str, &str> = std::collections::HashMap::with_capacity(2);
    x.insert("k1", "v1");
    x.insert("k2", "v2");
    let mut t = String::new();
    write!(t, "{:?}", x).unwrap();
    assert_eq!(t, "{\"k1\": \"v1\", \"k2\": \"v2\"}");
}

struct Complex64 {
    re: f64,
    im: f64,
}

fn get_name() -> std::borrow::Cow<'static, str> {
    std::env::var("USER")
        .map(|v| v.into())
        .unwrap_or("whoever you are".into())
}

impl std::fmt::Display for Complex64 {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let sign: char = if self.im < 0.0 { '-' } else { '+' };
        write!(f, "{} {} {}i", self.re, sign, f64::abs(self.im))
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值