Substring Checks With Contains And Boundaries

Test string membership with contains, starts_with, and ends_with, and remember that a pattern argument accepts chars as well as literal strings.

RustData Integrity

Code

rustsnippet
21 lines
fn main() {
    let url = "https://api.example.com/v2/orders";

    // 前缀与后缀:路由分类、扩展名判断的第一工具
    println!("https?: {}", url.starts_with("https://"));
    println!("json file: {}", url.ends_with(".json"));

    // contains 接受多种 pattern:字面串或字符谓词都行
    println!("has v2: {}", url.contains("v2"));
    println!("has digit: {}", url.contains(|c: char| c.is_ascii_digit()));

    // find 返回字节偏移,None 表示未命中
    println!("position of /v2: {:?}", url.find("/v2"));

    // 空串是任何字符串的前缀/后缀——校验时要防意外放行
    println!("empty prefix: {}", url.starts_with(""));

    // 大小写不敏感比较:先统一小写再判断
    let token = "Bearer ABC123";
    println!("bearer ok: {}", token.to_lowercase().starts_with("bearer "));
}

What the code does

Substring Checks With Contains And Boundaries keeps everything in the function main.

Using it

Each run prints the 7 labeled blocks https?:, json file:, has v2:, has digit:, position of /v2:, empty prefix:, bearer ok: in source order.

Key statements

let url = "https://api.example.com/v2/orders";
let token = "Bearer ABC123";

Interactive Tools for This Topic

FAQ

What does Substring Checks With Contains And Boundaries print when run?
The script runs standalone; its 7 labeled outputs include `https?:`, `json file:`, `has v2:`.