Last active
May 23, 2025 22:22
-
-
Save jweinst1/05045423520cdd219654bdc75fbc7531 to your computer and use it in GitHub Desktop.
indexing a string in rust.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::fs::File; | |
use std::io::prelude::*; | |
use std::io::SeekFrom; | |
use std::fs::OpenOptions; | |
#[derive(Debug)] | |
struct Seg(usize, usize); | |
impl Seg { | |
fn contains(&self, text:&[u8], term:&[u8]) -> bool { | |
let mut mode = false; | |
let mut idx = 0; | |
for i in self.0..(self.1 + 1) { | |
println!("i is {:?}", i); | |
if mode { | |
if text[i] == term[idx] { | |
idx += 1; | |
if idx == term.len() { | |
return true; | |
} | |
} else { | |
mode = false; | |
idx = 0; | |
} | |
} else { | |
if text[i] == term[0] { | |
println!("Got begin"); | |
mode = true; | |
idx += 1; | |
} | |
} | |
} | |
false | |
} | |
} | |
fn get_indexes(text:&[u8], delim:u8) -> Vec<Seg> { | |
let mut v = Vec::new(); | |
let mut last_idx = 0; | |
for i in 0..text.len() { | |
if text[i] == delim && i - last_idx > 1 { | |
v.push(Seg(last_idx + 1, i - 1)); | |
last_idx = i; | |
} | |
} | |
if (text.len() - 1 - last_idx) > 0 { | |
v.push(Seg(last_idx + 1, text.len() - 1)); | |
} | |
return v; | |
} | |
fn main() { | |
let foo = "\nfoobar\nfoobar\n4".to_string(); | |
let segs = get_indexes(foo.as_bytes(), b'\n'); | |
println!("{:?}", segs); | |
println!("{}", segs[0].contains(foo.as_bytes(),b"foobar")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment