【Rust】String


String类

===========================================

1、push_str

2、as_bytes

============================================

定义字符串

// 不可变
let s = String::from("hello");
// 可变
let mut s = String::from("hello");

1、push_str

给末尾追加字符串

#[cfg(not(no_global_oom_handling))]
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn push_str(&mut self, string: &str) {
    self.vec.extend_from_slice(string.as_bytes())
}

示例

s.push_str("aaa");

2、as_bytes

将字符串转化为字节数组

#[inline]
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn as_bytes(&self) -> &[u8] {
    &self.vec
}

示例

let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {// 元素索引,元素引用
    if item == b' ' {
        return i;
    }
}
// iter 返回集合中的每一个元素,enumerate包装返回的结果