forked from CocDap/Rust-Bootcamp-2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
strings.rs
112 lines (97 loc) · 2.56 KB
/
strings.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// Exercise 1
#[allow(dead_code)]
fn exercise1(color: &str) -> String {
let ans=color.to_string();
return ans;
}
// Exercise 2
// Fix all errors without adding newline
fn exercise2() -> String {
let mut s = String::from("hello");
s.push(',');
s =s+ " world!";
s
}
// Exercise 3
// Fix errors without removing any line
fn exercise3() -> String {
let s1 = String::from("hello,");
let s2 = " world!";
let s3 = s1+s2;
s3
}
// Exercise 4
// Reverse a string
fn reverse_string(input: &str) -> String {
input.chars().rev().collect()
}
// Exercise 5
// Check if a string is a palindrome
fn is_palindrome(word: &str) -> bool {
let vec: Vec<char> = word.chars().collect();
let size=vec.len();
for i in 0..size{
if vec[i]!=vec[size-1-i]{
return false;
}
}
true
}
// Exercise 6
// Count the occurrences of a character in a string
fn count_char_occurrences(string: &str, ch: char) -> usize {
let mut cnt=0;
for x in string.chars() {
if x==ch {
cnt=cnt+1;
}
}
cnt
}
#[cfg(test)]
mod tests {
use super::*;
// Test for exercise 1
#[test]
fn exercise1_work() {
assert_eq!("white".to_string(), exercise1("white"));
}
// Test for exercise 2
#[test]
fn exercise2_work() {
assert_eq!("hello, world!".to_string(), exercise2());
}
// Test for exercise 3
#[test]
fn exercise3_work() {
assert_eq!("hello, world!".to_string(), exercise3());
}
// Test for exercise 4
#[test]
fn test_reverse_string() {
assert_eq!(reverse_string("hello"), "olleh");
assert_eq!(reverse_string("rust"), "tsur");
assert_eq!(reverse_string("world"), "dlrow");
assert_eq!(reverse_string(""), "");
}
// Test for exercise 5
#[test]
fn test_palindrome() {
assert_eq!(is_palindrome("level"), true);
assert_eq!(is_palindrome("deed"), true);
assert_eq!(is_palindrome("Rotor"), true);
}
// Test for exercise 5
#[test]
fn test_non_palindrome() {
assert_eq!(is_palindrome("hello"), false);
assert_eq!(is_palindrome("world"), false);
}
// Test for exercise 6
#[test]
fn test_count_char_occurrences() {
assert_eq!(count_char_occurrences("Hello", 'l'), 2);
assert_eq!(count_char_occurrences("Rust is fun", 'u'), 1);
assert_eq!(count_char_occurrences("Mississippi", 's'), 4);
}
}