查找从给定索引开始的字符串 [英] Find a string starting from given index
问题描述
如果我不需要从 0 开始,如何找到子字符串的正确方法是什么?
What is the correct way how to find a substring if I need to start not from 0?
我有这个代码:
fn SplitFile(reader: BufReader<File>) {
for line in reader.lines() {
let mut l = line.unwrap();
// l contains "06:31:53.012 index0:2015-01-06 00:00:13.084
...
我需要找到第三个 :
并解析它后面的日期.仍然不知道该怎么做,因为 find
没有像 begin
这样的任何参数 - 请参阅 https://doc.rust-lang.org/std/string/struct.String.html#method.find.
I need to find third :
and parse the date behind it. Still no idea how to do it, because find
doesn't have any param like begin
- see https://doc.rust-lang.org/std/string/struct.String.html#method.find.
(我知道我可以使用正则表达式.我已经完成了,但我想比较性能 - 手动解析是否比使用正则表达式更快.</em>)
(I know I can use regex. I have it done, but I'd like to compare the performance - whether parsing by hand might the quicker than using regex.)
推荐答案
您说得对,在搜索字符串时似乎没有任何简单的方法可以跳过多个匹配项.不过,您可以手动完成.
You are right, there doesn't appear to be any trivial way of skipping several matches when searching a string. You can do it by hand though.
fn split_file(reader: BufReader<File>) {
for line in reader.lines() {
let mut l = &line.as_ref().unwrap()[..]; // get a slice
for _ in 0..3 {
if let Some(idx) = l.find(":") {
l = &l[idx+1..]
} else {
panic!("the line didn't have enough colons"); // you probably shouldn't panic
}
}
// l now contains the date
...
更新:
正如 faiface 指出的那样 下面,你可以用splitn()
来更简洁:
As faiface points out below, you can do this a bit cleaner with splitn()
:
fn split_file(reader: BufReader<File>) {
for line in reader.lines() {
let l = line.unwrap();
if let Some(datetime) = l.splitn(4, ':').last() {
// datetime now contains the timestamp string
...
} else {
panic!("line doesn't contain a timestamp");
}
}
}
你应该给他的答案点赞.
You should go upvote his answer.
这篇关于查找从给定索引开始的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!