1/********************************************************************
2 * Copyright (c) 2013 - 2014, Pivotal Inc.
3 * All rights reserved.
4 *
5 * Author: Zhanwei Wang
6 ********************************************************************/
7/********************************************************************
8 * 2014 -
9 * open source under Apache License Version 2.0
10 ********************************************************************/
11/**
12 * Licensed to the Apache Software Foundation (ASF) under one
13 * or more contributor license agreements. See the NOTICE file
14 * distributed with this work for additional information
15 * regarding copyright ownership. The ASF licenses this file
16 * to you under the Apache License, Version 2.0 (the
17 * "License"); you may not use this file except in compliance
18 * with the License. You may obtain a copy of the License at
19 *
20 * http://www.apache.org/licenses/LICENSE-2.0
21 *
22 * Unless required by applicable law or agreed to in writing, software
23 * distributed under the License is distributed on an "AS IS" BASIS,
24 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
25 * See the License for the specific language governing permissions and
26 * limitations under the License.
27 */
28#ifndef _HDFS_LIBHDFS3_COMMON_STRINGUTIL_H_
29#define _HDFS_LIBHDFS3_COMMON_STRINGUTIL_H_
30
31#include <string.h>
32#include <string>
33#include <vector>
34#include <cctype>
35
36namespace Hdfs {
37namespace Internal {
38
39static inline std::vector<std::string> StringSplit(const std::string & str,
40 const char * sep) {
41 char * token, *lasts = NULL;
42 std::string s = str;
43 std::vector<std::string> retval;
44 token = strtok_r(&s[0], sep, &lasts);
45
46 while (token) {
47 retval.push_back(token);
48 token = strtok_r(NULL, sep, &lasts);
49 }
50
51 return retval;
52}
53
54static inline std::string StringTrim(const std::string & str) {
55 int start = 0, end = str.length();
56
57 for (; start < static_cast<int>(str.length()); ++start) {
58 if (!std::isspace(str[start])) {
59 break;
60 }
61 }
62
63 for (; end > 0; --end) {
64 if (!std::isspace(str[end - 1])) {
65 break;
66 }
67 }
68
69 return str.substr(start, end - start);
70}
71
72static inline bool StringReplace(std::string& str, const std::string& from,
73 const std::string& to) {
74 size_t start_pos = str.find(from);
75
76 if (start_pos == std::string::npos) {
77 return false;
78 }
79
80 str.replace(start_pos, from.length(), to);
81 return true;
82}
83
84static inline bool StringReplaceAll(std::string& str, const std::string& from,
85 const std::string& to) {
86
87 if (from.empty()) {
88 return false;
89 }
90
91 bool retval = false;
92 size_t start_pos = 0;
93
94 while ((start_pos = str.find(from, start_pos)) != std::string::npos) {
95 str.replace(start_pos, from.length(), to);
96 start_pos += to.length();
97 retval = true;
98 }
99
100 return retval;
101}
102}
103}
104#endif /* _HDFS_LIBHDFS3_COMMON_STRINGUTIL_H_ */
105