1 /* 2 * Copyright (c) 2025-2025 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef OHOS_FORM_FWK_STRING_UTILS_H 17 #define OHOS_FORM_FWK_STRING_UTILS_H 18 19 #include <algorithm> 20 #include <functional> 21 #include <regex> 22 #include <string> 23 #include <vector> 24 25 namespace OHOS { 26 namespace AppExecFwk { 27 class StringUtils { 28 public: 29 // trim from start (in place) ltrim(std::string & inputStr)30 static inline void ltrim(std::string &inputStr) 31 { 32 inputStr.erase(inputStr.begin(), 33 std::find_if(inputStr.begin(), inputStr.end(), [](unsigned char ch) { return !std::isspace(ch); })); 34 } 35 36 // trim from end (in place) rtrim(std::string & inputStr)37 static inline void rtrim(std::string &inputStr) 38 { 39 inputStr.erase( 40 std::find_if(inputStr.rbegin(), inputStr.rend(), [](unsigned char ch) { return !std::isspace(ch); }).base(), 41 inputStr.end()); 42 } 43 44 // trim from both ends (in place) trim(std::string & inputStr)45 static inline void trim(std::string &inputStr) 46 { 47 ltrim(inputStr); 48 rtrim(inputStr); 49 } 50 split(const std::string & str,char delim)51 static inline std::vector<std::string> split(const std::string &str, char delim) 52 { 53 std::vector<std::string> tokens; 54 size_t start; 55 size_t end = 0; 56 while ((start = str.find_first_not_of(delim, end)) != std::string::npos) { 57 end = str.find(delim, start); 58 tokens.push_back(str.substr(start, end - start)); 59 } 60 return tokens; 61 } 62 VersionStrToNumber(std::string & versionStr,long long & versionNum)63 static inline bool VersionStrToNumber(std::string &versionStr, long long &versionNum) 64 { 65 std::smatch matchResults; 66 // version format: aa.bb.yy.rrr,example: 10.10.25.100 67 std::regex reg(R"(^\d{1,3}(\.\d{1,3}){1,3}$)"); 68 bool ret = std::regex_match(versionStr, matchResults, reg); 69 if (!ret) { 70 return false; 71 } 72 const char dot = '.'; 73 auto tokens = split(versionStr, dot); 74 std::string formatVersionStr; 75 for (const auto &token : tokens) { 76 auto tokenWithZero = std::string(3 - token.length(), '0') + token; 77 formatVersionStr.append(tokenWithZero); 78 } 79 versionNum = std::stoll(formatVersionStr); 80 return true; 81 } 82 }; 83 } // namespace AppExecFwk 84 } // namespace OHOS 85 #endif // OHOS_FORM_FWK_STRING_UTILS_H