1 /*
2  * Copyright (C) 2012 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5  * use this file except in compliance with the License. You may obtain a copy of
6  * the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13  * License for the specific language governing permissions and limitations under
14  * the License.
15  */
16 
17 #include <stdio.h>
18 #include <stdarg.h>
19 #include <stdlib.h>
20 
21 #include "Log.h"
22 #include "StringUtil.h"
23 
split(const android::String8 & str,char delimiter)24 std::vector<android::String8>* StringUtil::split(const android::String8& str, char delimiter)
25 {
26     std::vector<android::String8>* tokens = new std::vector<android::String8>();
27     unsigned int lastTokenEnd = 0;
28     for (unsigned int i = 0; i < str.length(); i++) {
29         if (str[i] == delimiter) {
30             if ((i - lastTokenEnd) > 0) {
31                 tokens->push_back(substr(str, lastTokenEnd, i - lastTokenEnd));
32             }
33             lastTokenEnd = i + 1; // 1 for skipping delimiter
34         }
35     }
36     if (lastTokenEnd < str.length()) {
37         tokens->push_back(substr(str, lastTokenEnd, str.length() - lastTokenEnd));
38     }
39     return tokens;
40 }
41 
substr(const android::String8 & str,size_t pos,size_t n)42 android::String8 StringUtil::substr(const android::String8& str, size_t pos, size_t n)
43 {
44     size_t l = str.length();
45 
46     if (pos >= l) {
47         android::String8 resultDummy;
48         return resultDummy;
49     }
50     if ((pos + n) > l) {
51         n = l - pos;
52     }
53     android::String8 result(str.string() + pos, n);
54     return result;
55 }
56 
compare(const android::String8 & str,const char * other)57 int StringUtil::compare(const android::String8& str, const char* other)
58 {
59     return strcmp(str.string(), other);
60 }
61 
endsWith(const android::String8 & str,const char * other)62 bool StringUtil::endsWith(const android::String8& str, const char* other)
63 {
64     size_t l1 = str.length();
65     size_t l2 = strlen(other);
66     const char* data = str.string();
67     if (l2 > l1) {
68         return false;
69     }
70     size_t iStr = l1 - l2;
71     size_t iOther = 0;
72     for(; iStr < l1; iStr++) {
73         if (data[iStr] != other[iOther]) {
74             return false;
75         }
76         iOther++;
77     }
78     return true;
79 }
80