String
2022/2/18 12:34:00
Rustの文字列オブジェクト
文字のコレクション
Rustの文字列オブジェクト
文字のコレクション
文字列を行ごとに繰り返すメソッド
let s = String::from("\
Rust:
safe, fast, productive.
Pick three.");
for line in s.lines() {
println!("{}", line);
}
文字列を小文字にするメソッド
assert_eq!("Rust".to_lowercase(), "rust");
assert_eq!(String::from("Rust").to_lowercase(), String::from("rust"));
文字列にクエリ文字列を含むか確認するメソッド
let s = String::from("safe, fast, productive.");
println!("{}", s.contains("duct")); //true
let s = "safe, fast, productive.";
println!("{}", s.contains("duct")); //true
fn main() {
let s = String::from("こんにちは世界");
for b in s.chars() {
println!("{}", b);
}
}
こ
ん
に
ち
は
世
界
Stringとu32の結合fn main() {
let s1 = String::from("Hello, ");
let s2 = 1234;
let s3 = s1 + &s2; // error!!!
println!("{}", s3);
}
error[E0308]: mismatched types
--> src\main.rs:4:19
|
4 | let s3 = s1 + &s2; // error!!!
| ^^^ expected `str`, found integer
|
= note: expected reference `&str`
found reference `&{integer}`
文字列といろんなものを結合できるすごい関数マクロ
Displayが実装されていればなんでも結合できる気がする(要検証)
String と Stringの結合let hello:String = String::from("hello");
let world:String = String::from("world");
let hello_world = format!("{} {}", hello, world);
println!("{}", hello_world); //hello world
String と 文字列リテラル(&str)の結合let hello:String = String::from("hello");
let world:&str = "world";
let hello_world = format!("{} {}", hello, world);
println!("{}", hello_world); //hello world
Stringと整数型(u32)の結合let hello:String = String::from("hello");
let number:u32 = 1234;
let hello_number = format!("{} {}", hello, number);
println!("{}", hello_number); //hello 1234
fn main() {
let mut string = String::new();
println!("{}", string); //
string.push_str("hello");
println!("{}", string); //hello
let s : &str = " world";
string.push_str(s);
println!("{}", string); //hello world
}
Stringは追加できない。エラーになる。StringにStringを追加(というか結合)したいときはformatを使おう。
追加元の変数にはmutをつけておく必要がある。変更されるので。
fn main() {
let s : &str = "Hello, world";
let string1 = s.to_string();
let string2 = "world hello".to_string();
let i = 1;
let string3 = i.to_string();
let string4 = 2.to_string();
println!("{}", string1); //Hello, world
println!("{}", string2); //world hello
println!("{}", string3); //1
println!("{}", string4); //2
}