1 /*
2 * Copyright (c) Huawei Technologies Co., Ltd. 2021. All rights reserved.
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 #include "string_utils.h"
16
EndsWith(const std::string & str,const std::string & postfix)17 bool StringUtils::EndsWith(const std::string& str, const std::string& postfix)
18 {
19 if (str.size() < postfix.size()) {
20 return false;
21 }
22 return str.compare(str.size() - postfix.size(), postfix.size(), postfix) == 0;
23 }
24
StartsWith(const std::string & str,const std::string & prefix)25 bool StringUtils::StartsWith(const std::string& str, const std::string& prefix)
26 {
27 if (str.size() < prefix.size()) {
28 return false;
29 }
30 return str.compare(0, prefix.size(), prefix) == 0;
31 }
32
Contains(const std::string & str,const std::string & target)33 bool StringUtils::Contains(const std::string& str, const std::string& target)
34 {
35 return str.find(target) != std::string::npos;
36 }
37
Strip(const std::string & str)38 std::string StringUtils::Strip(const std::string& str)
39 {
40 std::string blanks = " \f\v\t\r\n";
41
42 auto first = str.find_first_not_of(blanks);
43 if (first == std::string::npos) {
44 return "";
45 }
46
47 auto last = str.find_last_not_of(blanks);
48 if (last == std::string::npos) {
49 return "";
50 }
51 return str.substr(first, last - first + 1);
52 }
53
Join(const std::vector<std::string> & strs,const std::string & sep)54 std::string StringUtils::Join(const std::vector<std::string>& strs, const std::string& sep)
55 {
56 std::string result;
57 for (auto& s : strs) {
58 result += s;
59 result += sep;
60 }
61 if (result.size() > sep.size()) {
62 result.resize(result.size() - sep.size());
63 }
64 return result;
65 }
66
Split(const std::string & str,const std::string & sep)67 std::vector<std::string> StringUtils::Split(const std::string& str, const std::string& sep)
68 {
69 std::vector<std::string> result;
70 if (str.empty() || sep.empty() || str.size() < sep.size()) {
71 return result;
72 }
73 size_t start = 0; // start index
74 size_t pos = 0;
75 while (start < str.size()) {
76 pos = str.find(sep, start);
77 if (pos != std::string::npos) {
78 result.push_back(str.substr(start, pos - start));
79 start = pos + sep.size(); // next start index
80 } else {
81 // the last part
82 result.push_back(str.substr(start));
83 break;
84 }
85 }
86 return result;
87 }