Skip to content

Commit e954031

Browse files
committed
Auto merge of #26130 - steveklabnik:gh25986, r=alexcrichton
This can be confusing when whitespace is the separator Fixes #25986
2 parents 172cd83 + 96c7a6b commit e954031

File tree

1 file changed

+28
-3
lines changed

1 file changed

+28
-3
lines changed

src/libcollections/str.rs

+28-3
Original file line numberDiff line numberDiff line change
@@ -1180,9 +1180,8 @@ impl str {
11801180
/// matched by a pattern.
11811181
///
11821182
/// The pattern can be a simple `&str`, `char`, or a closure that
1183-
/// determines the split.
1184-
/// Additional libraries might provide more complex patterns like
1185-
/// regular expressions.
1183+
/// determines the split. Additional libraries might provide more complex
1184+
/// patterns like regular expressions.
11861185
///
11871186
/// # Iterator behavior
11881187
///
@@ -1224,6 +1223,32 @@ impl str {
12241223
/// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
12251224
/// assert_eq!(v, ["abc", "def", "ghi"]);
12261225
/// ```
1226+
///
1227+
/// If a string contains multiple contiguous separators, you will end up
1228+
/// with empty strings in the output:
1229+
///
1230+
/// ```
1231+
/// let x = "||||a||b|c".to_string();
1232+
/// let d: Vec<_> = x.split('|').collect();
1233+
///
1234+
/// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1235+
/// ```
1236+
///
1237+
/// This can lead to possibly surprising behavior when whitespace is used
1238+
/// as the separator. This code is correct:
1239+
///
1240+
/// ```
1241+
/// let x = " a b c".to_string();
1242+
/// let d: Vec<_> = x.split(' ').collect();
1243+
///
1244+
/// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1245+
/// ```
1246+
///
1247+
/// It does _not_ give you:
1248+
///
1249+
/// ```rust,ignore
1250+
/// assert_eq!(d, &["a", "b", "c"]);
1251+
/// ```
12271252
#[stable(feature = "rust1", since = "1.0.0")]
12281253
pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
12291254
core_str::StrExt::split(&self[..], pat)

0 commit comments

Comments
 (0)