1 //===-- StringExtras.cpp - Implement the StringExtras header --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the StringExtras.h header
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/StringExtras.h"
15 #include "llvm/ADT/SmallVector.h"
19 /// getToken - This function extracts one token from source, ignoring any
20 /// leading characters that appear in the Delimiters string, and ending the
21 /// token at any of the characters that appear in the Delimiters string. If
22 /// there are no tokens in the source string, an empty string is returned.
23 /// The Source source string is updated in place to remove the returned string
24 /// and any delimiter prefix from it.
25 std::string llvm::getToken(std::string &Source, const char *Delimiters) {
26 size_t NumDelimiters = std::strlen(Delimiters);
28 // Figure out where the token starts.
29 std::string::size_type Start =
30 Source.find_first_not_of(Delimiters, 0, NumDelimiters);
31 if (Start == std::string::npos) Start = Source.size();
33 // Find the next occurance of the delimiter.
34 std::string::size_type End =
35 Source.find_first_of(Delimiters, Start, NumDelimiters);
36 if (End == std::string::npos) End = Source.size();
38 // Create the return token.
39 std::string Result = std::string(Source.begin()+Start, Source.begin()+End);
41 // Erase the token that we read in.
42 Source.erase(Source.begin(), Source.begin()+End);
47 /// SplitString - Split up the specified string according to the specified
48 /// delimiters, appending the result fragments to the output list.
49 void llvm::SplitString(const std::string &Source,
50 std::vector<std::string> &OutFragments,
51 const char *Delimiters) {
52 std::string S = Source;
54 std::string S2 = getToken(S, Delimiters);
56 OutFragments.push_back(S2);
57 S2 = getToken(S, Delimiters);
61 void llvm::StringRef::split(SmallVectorImpl<StringRef> &A,
62 StringRef Separators, int MaxSplit,
63 bool KeepEmpty) const {
64 StringRef rest = *this;
66 // rest.data() is used to distinguish cases like "a," that splits into
67 // "a" + "" and "a" that splits into "a" + 0.
69 rest.data() != NULL && (MaxSplit < 0 || splits < MaxSplit);
71 std::pair<llvm::StringRef, llvm::StringRef> p = rest.split(Separators);
73 if (p.first.size() != 0 || KeepEmpty)
77 // If we have a tail left, add it.
78 if (rest.data() != NULL && (rest.size() != 0 || KeepEmpty))