Thrill  0.1
split_words.cpp
Go to the documentation of this file.
1 /*******************************************************************************
2  * tlx/string/split_words.cpp
3  *
4  * Part of tlx - http://panthema.net/tlx
5  *
6  * Copyright (C) 2016-2017 Timo Bingmann <[email protected]>
7  *
8  * All rights reserved. Published under the Boost Software License, Version 1.0
9  ******************************************************************************/
10 
12 
13 namespace tlx {
14 
15 std::vector<std::string> split_words(
16  const std::string& str, std::string::size_type limit) {
17  std::vector<std::string> out;
18  if (limit == 0) return out;
19 
20  std::string::const_iterator it = str.begin(), last = it;
21 
22  for ( ; it != str.end(); ++it)
23  {
24  if (*it == ' ' || *it == '\n' || *it == '\t' || *it == '\r')
25  {
26  if (it == last) { // skip over empty split substrings
27  last = it + 1;
28  continue;
29  }
30 
31  if (out.size() + 1 >= limit)
32  {
33  out.emplace_back(last, str.end());
34  return out;
35  }
36 
37  out.emplace_back(last, it);
38  last = it + 1;
39  }
40  }
41 
42  if (last != it)
43  out.emplace_back(last, it);
44 
45  return out;
46 }
47 
48 } // namespace tlx
49 
50 /******************************************************************************/
std::basic_string< char, std::char_traits< char >, Allocator< char > > string
string with Manager tracking
Definition: allocator.hpp:220
std::vector< std::string > split_words(const std::string &str, std::string::size_type limit)
Split the given string by whitespaces into distinct words.
Definition: split_words.cpp:15