C++ Rust String操作的比较

文档列表见:Rust 移动端跨平台复杂图形渲染项目开发系列总结(目录)

Rust字符串操作参考代码

C/C++ char数组和char *都可以转换成Rust byte String,然后用String提供的操作快速完成开发需求。

use std::str;

// This is "hello world" as an array of bytes.
// You can also start from a byte string b"hello world" and debug print that to get the
// utf8 encoded decimal values
println!("hello byte string: {:?}", b"hello world");

// OK so let's say you have an array of u8s
let array_of_u8 = [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100];

// [u8] to String (lossy)
// Any invalid bytes that are not utf8 will be replaced with
// the unicode replacement character '\u{FFFD}'
// You get a Cow (Clone on Write) not exactly a String
let string_utf8_lossy = String::from_utf8_lossy(&array_of_u8);
println!("string_utf8_lossy: {}", string_utf8_lossy);

// [u8] to String (result)
// The non-lossy version needs a vec not an array
let mut vec_of_u8 = vec![];
vec_of_u8.extend_from_slice(&array_of_u8);
let string_utf8_result = String::from_utf8(vec_of_u8).unwrap();
println!("string_utf8_result: {}", string_utf8_result);

// [u8] to str (result)
let str_utf8_result = str::from_utf8(&array_of_u8).unwrap();
println!("str_utf8_result: {}", str_utf8_result);

// [u8] to str (lossy)
// There is no str::from_utf8_lossy. Have to use String::from_utf8_lossy

// [u8] to Vec<char>
let vec_of_chars: Vec<char> = array_of_u8.iter().map(|byte| *byte as char).collect();
println!("vec_of_chars: {:?}", vec_of_chars);

// Vec<char> to Vec<u8>
let vec_of_u8s: Vec<u8> = vec_of_chars.iter().map(|c| *c as u8).collect();
println!("vec_of_u8s: {:?}", vec_of_u8s);

// Vec<char> to String
let mut string_of_collected_chars: String = vec_of_chars.iter().collect();
println!("string_of_collected_chars: {}", string_of_collected_chars);

// Now we have a mutable String. We can push chars
string_of_collected_chars.push('!');

// and we can push a str
string_of_collected_chars.push_str("!!");

// String to str
let str_slice = &string_of_collected_chars[..5];
println!("str_slice: {}", &str_slice);

// String to [u8]
let array_of_u8_from_string = string_of_collected_chars.as_bytes();
println!("array_of_u8_from_string: {:?}", array_of_u8_from_string);

// String to Vec<char>
let vec_of_chars_to_string: Vec<char> = string_of_collected_chars.chars().collect();
println!("vec_of_chars: {:?}", vec_of_chars_to_string);

// String from several Strings
let concat_strings = vec!["abc".to_string(), "def".to_string()].concat();
println!("concat_strings: {}", concat_strings);
let joined_strings = vec!["abc".to_string(), "def".to_string()].join("---");
println!("joined_strings: {}", joined_strings);
复制代码

字符串操作用C++与Rust分别实现

转换C/C++字符串为Rust字符串

Rust处理C/C++定义的字符串要稍微复杂些,为了尽可能复用Rust String类型定义的操作,需要把C/C++定义的字符串从char []char *转成u8数组,然后转成String,示例代码如下:

// shader_u8_slice相当于 char[COUNT]
let shader_u8_slice = b"\t#define\tDITHERAMOUNT\t0.5\n\t#define\tDITHERBIAS\t0.5\n";
let shader_byte_string = {
    let mut shader_u8_vec = vec![];
    shader_u8_vec.extend_from_slice(shader_u8_slice);
    unsafe { String::from_utf8_unchecked(shader_u8_vec) };
};
println!("replaced shader_byte_string:\n{}", shader_byte_string);
复制代码

全局替换字符串

C++替换source中所有的from子串为to子串,我现在想到的是做法是逐个查找、替换。Rust用String::replace()一个函数就够了。

void replace_all(string& source, const string& from, const string& to)
{
    auto pos = source.find(from);

    while (pos != string::npos)
    {
        source.replace(pos, from.size(), to);
        pos = source.find(from, pos + to.size());
    }
}
复制代码
// Heap allocate a string
let source = String::from("I like dogs");
// Allocate new memory and store the modified string there
let replaced_string: String = source.replace(from, to);
复制代码

前面的C/C++字符串转换成Rust String后,也可以调用String::replace()进行替换,示例代码如下:

let shader_u8_slice = b"\t#define\tDITHERAMOUNT\t0.5\n\t#define\tDITHERBIAS\t0.5\n";
let shader_byte_string = {
    let mut shader_u8_vec = vec![];
    shader_u8_vec.extend_from_slice(shader_u8_slice);
    let shader_byte_string = unsafe { String::from_utf8_unchecked(shader_u8_vec) };
    shader_byte_string.replace("\t", "    ")
};
println!("replaced shader_byte_string:\n{}", shader_byte_string);
复制代码

学习资料

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值