lmi-commits
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[lmi-commits] (no subject)


From: Greg Chicares
Subject: [lmi-commits] (no subject)
Date: Tue, 31 May 2016 21:06:22 +0000 (UTC)

branch: master
commit df2e3bdf3d4c655ce857d736a7d5650382cac1bf
Author: Gregory W. Chicares <address@hidden>
Date:   Tue May 31 16:14:14 2016 +0000

    Improve begins_with(), ends_with() algorithms
    
    substr() makes a copy, and rfind() might search the whole string;
    this reimplementation avoids such waste, and uses essentially the
    same algorithm for both functions.
---
 miscellany.cpp |   14 +++++++-------
 1 file changed, 7 insertions(+), 7 deletions(-)

diff --git a/miscellany.cpp b/miscellany.cpp
index 97e3e18..eed67ef 100644
--- a/miscellany.cpp
+++ b/miscellany.cpp
@@ -29,6 +29,7 @@
 #include "alert.hpp"
 #include "assert_lmi.hpp"
 
+#include <algorithm>                    // std::equal()
 #include <ctime>
 #include <fstream>
 #include <istream>
@@ -128,17 +129,16 @@ std::string htmlize(std::string const& raw_text)
 
 bool begins_with(std::string const& s, std::string const& prefix)
 {
-    return prefix == s.substr(0, prefix.size());
+    return
+           (prefix.size() <= s.size())
+        && std::equal(prefix.begin(), prefix.end(), s.begin());
 }
 
 bool ends_with(std::string const& s, std::string const& suffix)
 {
-    std::string::size_type pos = s.rfind(suffix);
-    if(std::string::npos == pos)
-        {
-        return false;
-        }
-    return s.substr(pos).size() == suffix.size();
+    return
+           (suffix.size() <= s.size())
+        && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
 }
 
 void ltrim(std::string& s, char const* superfluous)



reply via email to

[Prev in Thread] Current Thread [Next in Thread]