Skip to content

Commit 0f870c2

Browse files
committed
Implement swapcase method
1 parent 2e1c315 commit 0f870c2

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

src/cstring.c

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -521,6 +521,25 @@ PyObject *cstring_endswith(PyObject *self, PyObject *args) {
521521
return PyBool_FromLong(cmp == 0);
522522
}
523523

524+
PyDoc_STRVAR(swapcase__doc__, "");
525+
PyObject *cstring_swapcase(PyObject *self, PyObject *args) {
526+
struct cstring *new = CSTRING_ALLOC(Py_TYPE(self), Py_SIZE(self));
527+
const char *s = CSTRING_VALUE(self);
528+
char *d = CSTRING_VALUE(new);
529+
530+
for(;*s; ++s, ++d) {
531+
if(islower(*s)) {
532+
*d = toupper(*s);
533+
} else if(isupper(*s)) {
534+
*d = tolower(*s);
535+
} else {
536+
*d = *s;
537+
}
538+
}
539+
540+
return (PyObject *)new;
541+
}
542+
524543
PyDoc_STRVAR(upper__doc__, "");
525544
PyObject *cstring_upper(PyObject *self, PyObject *args) {
526545
struct cstring *new = CSTRING_ALLOC(Py_TYPE(self), Py_SIZE(self));
@@ -588,7 +607,7 @@ static PyMethodDef cstring_methods[] = {
588607
/* TODO: splitlines */
589608
{"startswith", cstring_startswith, METH_VARARGS, startswith__doc__},
590609
/* TODO: strip */
591-
/* TODO: swapcase */
610+
{"swapcase", cstring_swapcase, METH_VARARGS, swapcase__doc__},
592611
/* TODO: title */
593612
/* TODO: translate */
594613
{"upper", cstring_upper, METH_VARARGS, upper__doc__},

test/test_methods.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,3 +228,8 @@ def test_upper():
228228
target = cstring('hello123')
229229
assert target.upper() == cstring('HELLO123')
230230

231+
232+
def test_swapcase():
233+
target = cstring('hElLo, WoRlD 123')
234+
assert target.swapcase() == cstring('HeLlO, wOrLd 123')
235+

0 commit comments

Comments
 (0)