Implement Java String APIs in C++

Summary

It is another post related to String in C++. I will introduce some useful codes which implement APIs in Java String.

Content

  1. String.startsWith()
  2. String.endsWith()
  3. String.toLowerCase()
  4. String.toUpperCase()
  5. String.trim()

Detials

1. String.startsWith()

We implement a.startsWith(b) of java using C++.

bool starts_with(const string & a, const string & b) {
    return b == a.substr(0, b.size());
}
int main() {
        cout << starts_with("", "") << endl; 
        cout << starts_with("", "abcd") << endl; 
        cout << starts_with("abc", "abcd") << endl;
        cout << starts_with("abcd", "abcd") << endl;
        cout << starts_with("abcde", "abcd") << endl;
        cout << starts_with("abcde", "") << endl;
}
/*
1
0
0
1
1
1
*/

The complexity of substr and == should be linear to the size of string b.
Note that in a.substr(pos, len), if pos is greater than the string length, an out_of_range exception is thrown.

2. String.endsWith()

We implement a.endsWith(b) of java using C++.

bool ends_with(const string & a, const string & b) {
    return b.size() <= a.size() && b == a.substr(a.size() - b.size(), b.size());
}
int main() {
    cout << ends_with("", "") << endl;
    cout << ends_with("", "abc") << endl;
    cout << ends_with("abcd", "abc") << endl;
    cout << ends_with("abcd", "abcd") << endl;
    cout << ends_with("eabcd", "abcd") << endl;
    cout << ends_with("eabcd", "") << endl;
}
/*
1
0
0
1
1
1
*/

3. String.toLowerCase()

We have int tolower(int ch).

void to_lower(string & str) {
        for (auto && ch : str) {
                ch = tolower(ch);
        }
}
int main() {
    string str = "";
    to_lower(str); // ""

    str = "Hello World!";
    to_lower(str); // hello world!
}

4. String.toUpperCase()

We have int tolower(int ch).

void to_upper(string & str) {
        for (auto && ch : str) {
                ch = toupper(ch);
        }
}
int main() {
    string str = "";
    to_upper(str); // ""

    str = "Hello World!";
    to_upper(str); // HELLO WORLD!
}

5. String.trim()

string trim(const string & str) {
    if (str.empty()) {
        return str;
    }
    size_t left = 0, right = str.size() - 1;
    while (left < right && str[left] == ' ') {
        left++;
    }
    while (left < right && str[right] == ' ') {
        right++;
    }
    return str.substr(left, right - left + 1);
}

int main() {
    string str = "";
    cout << trim(str) << endl;

    str = "   Hello World!";
    cout << trim(str) << endl;

    str = "Hello World!   ";
    cout << trim(str) << endl;

    str = "   Hello World!   ";
    cout << trim(str) << endl;
}
/*
""
Hello World!
Hello World!   
Hello World!   
*/

Leave a Reply

Your email address will not be published. Required fields are marked *