Skip to content

Instantly share code, notes, and snippets.

@growingspaghetti
Last active November 26, 2017 16:55
Show Gist options
  • Save growingspaghetti/31abc000d4c0973c58c395d1d28a4332 to your computer and use it in GitHub Desktop.
Save growingspaghetti/31abc000d4c0973c58c395d1d28a4332 to your computer and use it in GitHub Desktop.
Those of StringUtils.substringBefore(), substringAfter(), and subStringBetween() are following in Rust. JavaのStringUtils.substringBefore(), substringAfter(), substringBetween()はRustでは以下かと(文字列操作)。 https://play.rust-lang.org/?gist=31abc000d4c0973c58c395d1d28a4332&version=undefined `cargo test -- --nocapture` for println!()
fn substring_before(body: &str, separator: &str) -> String {
match body.find(separator) {
Some(i) => body.get(..i).unwrap().to_string(),
None => body.to_string(),
}
}
fn substring_after(body: &str, separator: &str) -> String {
match body.find(separator) {
Some(i) => body.get(i+separator.len()..).unwrap().to_string(),
None => body.to_string(),
}
}
fn substring_between(body: &str, open: &str, close: &str) -> String {
match body.find(open) {
Some(i) => {
let after = body.get(i+open.len()..).unwrap();
match after.find(close) {
Some(i) => after.get(..i).unwrap().to_string(),
None => body.to_string(),
}
},
None => body.to_string(),
}
}
#[test]
fn test_substring_before() {
let test_url = "https://doc.rust-lang.org/book/first-edition/documentation.html";
let test_expected_url = "https://doc.rust-lang.org";
assert_eq!(test_expected_url, substring_before(test_url, "/book"));
let test_emojis = "🗻∈🌏";
assert_eq!(Some("🗻"), test_emojis.get(0..4));
println!("{:?}", test_emojis.get(..test_emojis.len()));
assert_eq!("🗻∈", substring_before(test_emojis, "🌏"));
}
#[test]
fn test_substring_after() {
let test_url = "https://doc.rust-lang.org/book/first-edition/documentation.html";
let test_expected_url = "doc.rust-lang.org/book/first-edition/documentation.html";
assert_eq!(test_expected_url, substring_after(test_url, "https://"));
let test_emojis = "🗻∈🌏";
assert_eq!(Some("🗻"), test_emojis.get(0..4));
println!("{:?}", test_emojis.get(..test_emojis.len()));
assert_eq!("∈🌏", substring_after(test_emojis, "🗻"));
}
#[test]
fn test_substring_between() {
let test_url = "https://doc.rust-lang.org/book/first-edition/documentation.html";
let test_expected_url = "doc.rust-lang.org";
assert_eq!(test_expected_url, substring_between(test_url, "https://", "/"));
let test_emojis = "🗻∈🌏";
assert_eq!(Some("🗻"), test_emojis.get(0..4));
println!("{:?}", test_emojis.get(..test_emojis.len()));
assert_eq!("∈", substring_between(test_emojis, "🗻", "🌏"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment