tlx
contains_word.cpp
Go to the documentation of this file.
1/*******************************************************************************
2 * tlx/string/contains_word.cpp
3 *
4 * Part of tlx - http://panthema.net/tlx
5 *
6 * Copyright (C) 2016-2017 Timo Bingmann <tb@panthema.net>
7 *
8 * All rights reserved. Published under the Boost Software License, Version 1.0
9 ******************************************************************************/
10
12
13namespace tlx {
14
15static inline bool is_white(char c) {
16 return c == ' ' || c == '\n' || c == '\t' || c == '\r';
17}
18
19bool contains_word(const std::string& str, const char* word) {
20
21 // all strings contain the empty word
22 if (*word == 0)
23 return true;
24
25 std::string::const_iterator it = str.begin();
26
27 while (it != str.end())
28 {
29 // skip over whitespace
30 while (is_white(*it)) {
31 if (++it == str.end()) return false;
32 }
33
34 // check if this non-whitespace matches the string
35 const char* wi = word;
36 while (*it == *wi) {
37 ++it, ++wi;
38 if (*wi == 0) {
39 if (it == str.end() || is_white(*it))
40 return true;
41 else break;
42 }
43 if (it == str.end()) return false;
44 }
45
46 // skip over not matching whitespace
47 while (!is_white(*it)) {
48 if (++it == str.end()) return false;
49 }
50 }
51
52 return false;
53}
54
55bool contains_word(const std::string& str, const std::string& word) {
56
57 // all strings contain the empty word
58 if (word.empty())
59 return true;
60
61 std::string::const_iterator it = str.begin();
62
63 while (it != str.end())
64 {
65 // skip over whitespace
66 while (is_white(*it)) {
67 if (++it == str.end()) return false;
68 }
69
70 // check if this non-whitespace matches the string
71 std::string::const_iterator wi = word.begin();
72 while (*it == *wi) {
73 ++it, ++wi;
74 if (wi == word.end()) {
75 if (it == str.end() || is_white(*it))
76 return true;
77 else break;
78 }
79 if (it == str.end()) return false;
80 }
81
82 // skip over not matching whitespace
83 while (!is_white(*it)) {
84 if (++it == str.end()) return false;
85 }
86 }
87
88 return false;
89}
90
91} // namespace tlx
92
93/******************************************************************************/
bool contains_word(const std::string &str, const char *word)
Search the given string for a whitespace-delimited word.
static bool is_white(char c)