1.字符串转换为字符数组:
//分配内存存储HellWorld并使用s指针指向该地址
let mut s = String::from("HelloWorld");
println!("s=> {}",s);
//转换字符串为字符数组
let b=s.as_bytes();
2.遍历字符数组
//遍历字符数组
for c in b {
println!("char of String s : {}",c);
}
输出:
char of String s : 72
char of String s : 101
char of String s : 108
char of String s : 108
char of String s : 111
char of String s : 87
char of String s : 111
char of String s : 114
char of String s : 108
char of String s : 100
3.使用数组枚举器遍历:
//通过数组枚举器遍历
for (index,&c) in b.iter().enumerate() {
println!("index:{},char:{}",index,c);
}
输出:
index:0,char:72
index:1,char:101
index:2,char:108
index:3,char:108
index:4,char:111
index:5,char:87
index:6,char:111
index:7,char:114
index:8,char:108
index:9,char:100
4.子字符串操作
//取字符串指定长度的任意位置开始与任意位置结束的子字符串
let s1 = &s[0..5];//取索引0到4的字符
let s2=&s[5..10];//取索引5到9的字符
println!("chars of {},[0~4]=> {},[5~9]=> {}",s,s1,s2);
//取字符串长度
println!("{},{},{}",s.len(),s1.len(),s2.len());
输出:
chars of HelloWorld,[0~4]=> Hello,[5~9]=> World
10,5,5
5.字符串中空格判断
//清空字符串,s必须是可变量才能调用clear
s.clear();
println!("s.clear after => {}",s);
//字符串中空格判断
s.push_str("Hello Wolrd");//重新压入字符串
for (i,&c) in s.as_bytes().iter().enumerate() {
if c==b' ' {
println!("空格所在位置索引: {}",i);
break;//找到空格就跳出
}
}
println!("s from push_str => {}",s);
//使用空格分割字符串
for str in s.split(' ') {
println!("part of s => {}",str);
}
//去掉字符串空格
println!("old: {} replace => {}",s, s.replace(" ",""));
6.数组元素验证:
//数组验证: ['H','e','l','l','0',' ','W','o','r','l','d']
let x=&s[1..3];
println!("{}",x);
assert_eq!(&s[1..3],"el");
7.完整示例代码:
fn main() {
println!("RUST语言SLICE(切片)类型");
//分配内存存储HellWorld并使用s指针指向该地址
let mut s = String::from("HelloWorld");
println!("s=> {}",s);
//转换字符串为字符数组
let b=s.as_bytes();
//遍历字符数组
for c in b {
println!("char of String s : {}",c);
}
//通过数组枚举器遍历
for (index,&c) in b.iter().enumerate() {
println!("index:{},char:{}",index,c);
}
//取字符串指定长度的任意位置开始与任意位置结束的子字符串
let s1 = &s[0..5];//取索引0到4的字符
let s2=&s[5..10];//取索引5到9的字符
println!("chars of {},[0~4]=> {},[5~9]=> {}",s,s1,s2);
//取字符串长度
println!("{},{},{}",s.len(),s1.len(),s2.len());
//清空字符串,s必须是可变量才能调用clear
s.clear();
println!("s.clear after => {}",s);
//字符串中空格判断
s.push_str("Hello Wolrd");//重新压入字符串
for (i,&c) in s.as_bytes().iter().enumerate() {
if c==b' ' {
println!("空格所在位置索引: {}",i);
break;//找到空格就跳出
}
}
println!("s from push_str => {}",s);
//使用空格分割字符串
for str in s.split(' ') {
println!("part of s => {}",str);
}
//去掉字符串空格
println!("old: {} replace => {}",s, s.replace(" ",""));
//数组验证: ['H','e','l','l','0',' ','W','o','r','l','d']
let x=&s[1..3];
println!("{}",x);
assert_eq!(&s[1..3],"el");
}
运行输出: