How to do it...

  1. In the folder src/bin, create a file called string.rs.
  2. Add the following code, and run it with cargo run --bin string:
1   fn main() {
2 // As a String is a kind of vector,
3 // you can construct them the same way
4 let mut s = String::new();
5 s.push('H'),
6 s.push('i'),
7 println!("s: {}", s);
8
9 // The String however can also be constructed
10 // from a string slice (&str)
11 // The next two ways of doing to are equivalent
12 let s = "Hello".to_string();
13 println!("s: {}", s);
14 let s = String::from("Hello");
15 println!("s: {}", s);
16
17 // A String in Rust will always be valid UTF-8
18 let s = " Þjóðhildur ".to_string();
19 println!("s: {}", s);
20
21 // Append strings to each other
22 let mut s = "Hello ".to_string();
23 s.push_str("World");
24
25 // Iterate over the character
26 // A "character" is defined here as a
27 // Unicode Scalar Value
28 for ch in "Tubular".chars() {
29 print!("{}.", ch);
30 }
31 println!();
32 // Be careful though, a "character" might not
33 // always be what you expect
34 for ch in "y̆".chars() {
35 // This does NOT print y̆
36 print!("{} ", ch);
37 }
38 println!();

Use the following code to split a string in various ways:

42    // Split a string slice into two halves
43 let (first, second) = "HelloThere".split_at(5);
44 println!("first: {}, second: {}", first, second);
45
46 // Split on individual lines
47 let haiku = "
48 she watches
49 satisfied after love
50 he lies
51 looking up at nothing
52 ";
53 for line in haiku.lines() {
54 println!(" {}.", line);
55 }
56
57 // Split on substrings
58 for s in "Never;Give;Up".split(';') {
59 println!("{}", s);
60 }
61 // When the splitted string is at the beginning or end,
62 // it will result in the empty string
63 let s: Vec<_> = "::Hi::There::".split("::").collect();
64 println!("{:?}", s);
65
66 // If you can eliminate the empty strings at the end
67 // by using split_termitor
68 let s: Vec<_> = "Mr. T.".split_terminator('.').collect();
69 println!("{:?}", s);
70
71 // char has a few method's that you can use to split on
72 for s in "I'm2fast4you".split(char::is_numeric) {
73 println!("{}", s);
74 }
75
76 // Split only a certain amount of times
77 for s in "It's not your fault, it's mine".splitn(3,
char::is_whitespace) {
78 println!("{}", s);
79 }
80
81 // Get only the substrings that match a pattern
82 // This is the opposite of splitting
83 for c in "The Dark Knight rises".matches(char::is_uppercase) {
84 println!("{}", c);
85 }
86
87 // Check if a string starts with something
88 let saying = "The early bird gets the worm";
89 let starts_with_the = saying.starts_with("The");
90 println!(
"Does "{}" start with "The"?: {}",
saying,
starts_with_the
);
91 let starts_with_bird = saying.starts_with("bird");
92 println!(
"Does "{}" start with "bird"?: {}",
saying,
starts_with_bird
);
93
94 // Check if a string ends with something
95 let ends_with_worm = saying.ends_with("worm");
96 println!("Does "{}" end with "worm"?: {}", saying,
ends_with_worm);
97
98 // Check if the string contains something somewhere
99 let contains_bird = saying.contains("bird");
100 println!("Does "{}" contain "bird"?: {}", saying,
contains_bird);

Remove whitespace:

105   // Splitting on whitespace might not result in what you expect
106 let a_lot_of_whitespace = " I love spaaace ";
107 let s: Vec<_> = a_lot_of_whitespace.split(' ').collect();
108 println!("{:?}", s);
109 // Use split_whitespace instead
110 let s: Vec<_> =
a_lot_of_whitespace.split_whitespace().collect();
111 println!("{:?}", s);
112
113 // Remove leading and trailing whitespace
114 let username = " P3ngu1n ".trim();
115 println!("{}", username);
116 // Remove only leading whitespace
117 let username = " P3ngu1n ".trim_left();
118 println!("{}", username);
119 // Remove only trailing whitespace
120 let username = " P3ngu1n ".trim_right();
121 println!("{}", username);
122
123
124 // Parse a string into another data type
125 // This requires type annotation
126 let num = "12".parse::<i32>();
127 if let Ok(num) = num {
128 println!("{} * {} = {}", num, num, num * num);
129 }

Modify the string:

133   // Replace all occurences of a pattern
134 let s = "My dad is the best dad";
135 let new_s = s.replace("dad", "mom");
136 println!("new_s: {}", new_s);
137
138 // Replace all characters with their lowercase
139 let lowercase = s.to_lowercase();
140 println!("lowercase: {}", lowercase);
141
142 // Replace all characters with their uppercase
143 let uppercase = s.to_uppercase();
144 println!("uppercase: {}", uppercase);
145
146 // These also work with other languages
147 let greek = "ὈΔΥΣΣΕΎΣ";
148 println!("lowercase greek: {}", greek.to_lowercase());
149
150 // Repeat a string
151 let hello = "Hello! ";
152 println!("Three times hello: {}", hello.repeat(3));
153 }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.198.83