Commit c8579e00 authored by Kevin Modzelewski's avatar Kevin Modzelewski

Merge pull request #111 from kkszysiu/str_capitalize_and_title

Added capitalize and title functions for strings
parents c95d763e 76bcee2a
......@@ -477,6 +477,50 @@ Box* strRStrip(BoxedString* self, Box* chars) {
}
}
Box* strCapitalize(BoxedString* self) {
assert(self->cls == str_cls);
std::string s(self->s);
for (auto& i : s) {
if (std::isupper(i)) {
i = std::tolower(i);
}
}
if (!s.empty()) {
if (std::islower(s[0])) {
s[0] = std::toupper(s[0]);
}
}
return boxString(s);
}
Box* strTitle(BoxedString* self) {
assert(self->cls == str_cls);
std::string s(self->s);
bool start_of_word = false;
for (auto& i : s) {
if (std::islower(i)) {
if (!start_of_word) {
i = std::toupper(i);
}
start_of_word = true;
} else if (std::isupper(i)) {
if (start_of_word) {
i = std::tolower(i);
}
start_of_word = true;
} else {
start_of_word = false;
}
}
return boxString(s);
}
Box* strContains(BoxedString* self, Box* elt) {
assert(self->cls == str_cls);
if (elt->cls != str_cls)
......@@ -617,6 +661,9 @@ void setupStr() {
str_cls->giveAttr("rstrip", new BoxedFunction(boxRTFunction((void*)strRStrip, STR, 2, 1, false, false), { None }));
str_cls->giveAttr("capitalize", new BoxedFunction(boxRTFunction((void*)strCapitalize, STR, 1)));
str_cls->giveAttr("title", new BoxedFunction(boxRTFunction((void*)strTitle, STR, 1)));
str_cls->giveAttr("__contains__", new BoxedFunction(boxRTFunction((void*)strContains, BOXED_BOOL, 2)));
str_cls->giveAttr("__add__", new BoxedFunction(boxRTFunction((void*)strAdd, UNKNOWN, 2)));
......
# Testing capitalize/title methods.
def test(s):
print 'string:', repr(s), 'capitalize:', s.capitalize(), 'titLe:', s.titLe()
test(' hello ')
test('Hello ')
test('hello ')
test('aaaa')
test('AaAa')
test('fOrMaT thIs aS titLe String')
test('fOrMaT,thIs-aS*titLe;String')
test('getInt')
var = 'hello'
try:
var.capitalize(42)
print 'TypeError not raised'
except TypeError:
print 'TypeError raised'
var = 'hello'
try:
var.title(42)
print 'TypeError not raised'
except TypeError:
print 'TypeError raised'
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment