string_format/lib.rs
1///Format the two strings together
2/// # Examples
3///
4/// ```
5/// extern crate string_format;
6/// use string_format::*;
7/// let hello = String::from("hello {}");
8/// let world = String::from("world");
9/// assert_eq!("hello world".to_string(), string_format(hello, world));
10/// ```
11pub fn string_format(string : String, text : String) -> String {
12 let mut result = string.clone();
13 //loop throught the String to find the first pair of brackets
14 match string.find("{}") {
15 Some(offset) => {
16 result.replace_range(offset..offset+2, &text);
17 result
18 }
19 None => { string }
20 }
21}
22
23///work like the format! macro but with a String
24/// # Example
25/// ```
26/// # #[macro_use] extern crate string_format;
27/// # fn main(){
28/// use string_format::*;
29///
30/// let hello = String::from("hello {} {}");
31/// let cruel = String::from("cruel");
32/// let world = String::from("world");
33/// assert_eq!("hello cruel world".to_string(), string_format!(hello, cruel, world));
34/// # }
35/// ```
36#[macro_export]
37macro_rules! string_format {
38 ($($arg:expr),*) => {{
39 let text = String::from("{}");
40 $(
41 let text = string_format(text, $arg);
42 )*
43 text
44 }}
45}
46
47#[cfg(test)]
48mod tests {
49 use super::*;
50
51 #[test]
52 fn test_string_format() {
53 assert_eq!("hello world".to_string(), string_format("hello {}".to_string(), "world".to_string()));
54 }
55
56 #[test]
57 fn test_string_format_macro(){
58 let hello = String::from("hello {} {}");
59 let cruel = String::from("cruel");
60 let world = String::from("world");
61 assert_eq!("hello cruel world".to_string(), string_format!(hello, cruel, world));
62 }
63}