-
Notifications
You must be signed in to change notification settings - Fork 1
/
1.rs
68 lines (54 loc) · 1.56 KB
/
1.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use std::io;
// Pattern to be searched for.
const PATTERN : &str = "ould";
/// A program to test pattern search.
fn main()
{
let mut input = String::new();
loop {
match io::stdin().read_line(&mut input) {
Ok (_bytes) => {
if _bytes == 0 {
break;
}
let trimmed_input = input.trim_end();
let pos: i32 = strindex(trimmed_input, PATTERN);
print!("[*] Rightmost position of '{}' in '{}' is: '{}'\n", PATTERN, trimmed_input, pos);
// clear input so lines don't get appended
input.clear();
},
Err(_) => {
panic!("Unexpected error.");
}
}
}
}
/// A function to check for the rightmost occurrence of t in s.
///
/// @param &str s The string to be searched at
/// @param &str t The pattern to be searched for
///
/// @return i32 Position of rightmost occurrence of t inside s.
fn strindex(s: &str, t: &str) -> i32
{
let mut rightmost : i32 = -1;
for (idx, _) in s.chars().enumerate() {
let mut str_iter = s.chars().skip(idx+1);
let mut pattern_iter = t.chars();
let mut k = 0;
let pend;
loop {
let _sc = str_iter.next();
let _pc = pattern_iter.next();
if _pc == None || _sc != _pc {
pend = _pc;
break;
}
k += 1;
};
if k > 0 && pend == None {
rightmost = (idx+1) as i32;
}
}
rightmost
}