Skip to content

Commit 730d86b

Browse files
committed
Utility::contains(), Utility::ends_with()
You'd think these would be easy enough to implement ourselves, but we had a bug in our idiom for ends_with(), so let's just consolidate everything. I'll give these names to match C++20/23 standard names, both for an easier transition in the future and to reassure myself that I'm not the only one who was bad enough with string utilities to benefit from these helper functions.
1 parent d1acc0a commit 730d86b

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

include/utils/utility.h

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,20 @@ void deallocate (std::vector<T> & vec)
386386
std::string_view basename_of(const std::string & fullname);
387387

388388

389+
/**
390+
* Look for a substring within a string.
391+
*/
392+
bool contains(std::string_view superstring,
393+
std::string_view substring);
394+
395+
396+
/**
397+
* Look for a substring at the very end of a string.
398+
*/
399+
bool ends_with(std::string_view superstring,
400+
std::string_view suffix);
401+
402+
389403
// Utility functions useful when dealing with complex numbers.
390404

391405
#ifdef LIBMESH_USE_COMPLEX_NUMBERS

src/utils/utility.C

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,5 +202,27 @@ std::string Utility::unzip_file (std::string_view name)
202202

203203

204204

205+
bool Utility::contains(std::string_view superstring, std::string_view substring)
206+
{
207+
// This can just be C++23 contains() someday
208+
return superstring.find(substring) != std::string::npos;
209+
}
210+
211+
212+
213+
bool Utility::ends_with(std::string_view superstring,
214+
std::string_view suffix)
215+
{
216+
// This can just be C++20 ends_with() someday
217+
const auto sufsize = suffix.size();
218+
const auto supsize = superstring.size();
219+
if (sufsize > supsize)
220+
return false;
221+
222+
return superstring.compare(supsize - sufsize, std::string::npos,
223+
suffix) == 0;
224+
}
225+
226+
205227

206228
} // namespace libMesh

0 commit comments

Comments
 (0)