Skip to content

Commit 517e34c

Browse files
committed
Add string_utils for cmdstan
1 parent 026ede6 commit 517e34c

3 files changed

Lines changed: 56 additions & 25 deletions

File tree

src/stan/io/ends_with.hpp

Lines changed: 0 additions & 23 deletions
This file was deleted.

src/stan/io/string_utils.hpp

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,60 @@ inline void remove_first(std::string& input,
102102
}
103103
}
104104

105+
/**
106+
* Replaces the first occurrence of a substring in a string in place.
107+
*
108+
* @param input string to modify
109+
* @param substring substring to replace
110+
* @param replacement replacement string
111+
*/
112+
inline void replace_first(std::string& input,
113+
const std::string_view& substring,
114+
const std::string_view& replacement) {
115+
const std::size_t position = input.find(substring);
116+
if (position != std::string::npos) {
117+
input.replace(position, substring.size(), replacement);
118+
}
119+
}
120+
121+
/**
122+
* Tests whether a string contains a substring.
123+
*
124+
* @param input string to test
125+
* @param substring substring to look for
126+
* @return true if input contains substring
127+
*/
128+
inline bool contains(const std::string_view& input,
129+
const std::string_view& substring) {
130+
return input.find(substring) != std::string_view::npos;
131+
}
132+
133+
/**
134+
* Tests whether a string ends with a suffix.
135+
*
136+
* @param input string to test
137+
* @param suffix suffix to look for
138+
* @return true if input ends with suffix
139+
*/
140+
inline bool ends_with(const std::string_view& input,
141+
const std::string_view& suffix) {
142+
return input.size() >= suffix.size()
143+
&& input.substr(input.size() - suffix.size()) == suffix;
144+
}
145+
146+
/**
147+
* Tests whether a string starts with a prefix.
148+
*
149+
* @param input string to test
150+
* @param prefix prefix to look for
151+
* @return true if input starts with prefix
152+
*/
153+
inline bool starts_with(const std::string_view& input,
154+
const std::string_view& prefix) {
155+
return input.size() >= prefix.size()
156+
&& input.substr(0, prefix.size()) == prefix;
157+
}
158+
105159
} // namespace io
106160
} // namespace stan
107161

src/test/unit/io/ends_with_test.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
#include <stan/io/ends_with.hpp>
1+
#include <stan/io/string_utils.hpp>
22
#include <gtest/gtest.h>
33
#include <string>
44

55
void expect_ends(const std::string& p, const std::string& s, bool cond) {
6-
EXPECT_EQ(cond, stan::io::ends_with(p, s));
6+
EXPECT_EQ(cond, stan::io::ends_with(s, p));
77
}
88

99
TEST(Io, EndsWith) {

0 commit comments

Comments
 (0)