&str
2022/2/19 5:43:00
文字列を小文字にするメソッド
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() {
for b in "こんにちは".bytes() {
println!("{}", b);
}
println!("");
let s:&str = "世界";
for b in s.bytes() {
println!("{}", b);
}
}
227
129
147
227
130
147
227
129
171
227
129
161
227
129
175
228
184
150
231
149
140
fn main() {
for c in "こんにちは".chars() {
println!("{}", c);
}
println!("");
let s:&str = "世界";
for c in s.chars() {
println!("{}", c);
}
}
こ
ん
に
ち
は
世
界
&strと&strの結合fn main() {
let s1:&str = "Hello, ";
let s2:&str = "world!";
let s3 = s1 + &s2; // error!!!
println!("{}", s3);
}
error[E0369]: cannot add `&&str` to `&str`
--> src\main.rs:4:17
|
4 | let s3 = s1 + &s2; // error!!!
| -- ^ --- &&str
| | |
| | `+` cannot be used to concatenate two `&str` strings
| &str
|
help: `to_owned()` can be used to create an owned `String` from a string reference. String concatenation appends the string on the right to the string on the left and may require reallocation. This requires ownership of the string on the left
|
4 | let s3 = s1.to_owned() + &s2; // error!!!
| ~~~~~~~~~~~~~
文字列といろんなものを結合できるすごい関数マクロ
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をつけておく必要がある。変更されるので。
https://qiita.com/aflc/items/f2be832f9612064b12c6#文字列リテラルはstr
文字列スライスの参照
strの借用された形態
fn main() {
let s : &str = "Hello, world";
println!("{}", s); //Hello, world
}