home   articles   tags   browse code   

C++ substr function


 

The STL provides us with substr function, but it is lacking. For one it requires 2 parameters, instead of defaulting on the second. The php substr function also provides the ability to use negative 'start' position and negative lengths.

#include <iostream>
#include <string>

using namespace std;

string substr(const string &str, int start);
string substr(const string &str, int start, int length);

int main(int argc, char *argv[])
{
    cout << substr("abcdef", -1) << endl;     // "f"
    cout << substr("abcdef", -2) << endl;     // "ef"
    cout << substr("abcdef", -3, 1) << endl;  // "d"

    cout << substr("abcdef", 0, -1) << endl;  // "abcde"
    cout << substr("abcdef", 2, -1) << endl;  // "cde"
    cout << substr("abcdef", 4, -4) << endl;  // ""
    cout << substr("abcdef", -3, -1) << endl; // "de"

    cout << substr("abcdef", 1) << endl;      // "bcdef"
    cout << substr("abcdef", 1, 3) << endl;   // "bcd"
    cout << substr("abcdef", 0, 4) << endl;   // "abcd"
    cout << substr("abcdef", 0, 8) << endl;   // "abcdef"
    cout << substr("abcdef", -1, 1) << endl;  // "f"
}

string substr(const string &str, int start)
{
    return substr(str,start,str.length());
}
string substr(const string &str, int start, int length)
{
    if (start  < 0 ) start+=str.length();
    if (length < 0 ) length=str.length()+length-start;
    if (length < 0 ) return "";
    return str.substr(start,length);
}


I used test cases from the php website. Having 2 functions the same name with slightly different parameters is an example of function overloading. This function allows for negative starts and negative lengths, to mimic the php string function.
 

Tags: c++
 


 

 



Related Articles
 


home  |  privacy policy  |  terms of use  |  contact  


©2010, Zedwood Digital