LoginSignup
2
1

More than 1 year has passed since last update.

Rustで文字列に特定の文字が含まれるかどうかを判定する方法

Last updated at Posted at 2023-02-21

contains

let s = "hello";
if s.contains("l") {
    println!("'l' is in the string!");
}

指定した文字列が、対象の文字列に含まれる場合に true を、含まれない場合に false を返します。
もっとも一般的な方法かと。
戻り値:bool

find

let s = "hello";
if s.find("l").is_some() {
    println!("'l' is in the string!");
}

指定した文字列が対象の文字列に含まれる場合は、その最初の出現箇所のインデックスを Some で返します。含まれない場合は None を返します。
戻り値:Option

matches

let s = "hello";
if s.matches("l").count() > 0 {
    println!("'l' is in the string!");
}

正規表現のパターン文字列を指定し、対象の文字列にパターンがマッチするすべての箇所のイテレータを返します。
戻り値:Matches<'a, P>

is_match

use regex::Regex;
let s = "hello";
let re = Regex::new(r"l").unwrap();
if re.is_match(s) {
    println!("'l' is in the string!");
}

正規表現のパターン文字列を指定し、対象の文字列がパターンにマッチする場合に true を、マッチしない場合に false を返します。
戻り値:bool

char_indices

let s = "hello";
if s.char_indices().any(|(_, c)| c == 'l') {
    println!("'l' is in the string!");
}

文字列に含まれる各文字のインデックスとその文字を順に返すイテレータを生成するメソッドです。

番外編

starts_with

let s = "hello";
if s.starts_with("he") {
    println!("'hello' starts with 'he'!");
}

対象の文字列が、指定した文字列で始まる場合に true を、始まらない場合に false を返します。
戻り値:bool

ends_with

let s = "hello";
if s.ends_with("lo") {
    println!("'hello' ends with 'lo'!");
}

対象の文字列が、指定した文字列で終わる場合に true を、終わらない場合に false を返します。
戻り値:bool

2
1
2

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
2
1