Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f6312b5

Browse files
committed
Implement split method
1 parent ecd8bc1 commit f6312b5

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

src/cstring.c

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -580,6 +580,33 @@ PyObject *cstring_startswith(PyObject *self, PyObject *args) {
580580
return PyBool_FromLong(cmp == 0);
581581
}
582582

583+
PyDoc_STRVAR(strip__doc__, "");
584+
PyObject *cstring_strip(PyObject *self, PyObject *args) {
585+
PyObject *charsobj = NULL;
586+
if(!PyArg_ParseTuple(args, "|O", &charsobj))
587+
return NULL;
588+
589+
const char *chars = " \t\n\v\f\r";
590+
591+
if(charsobj && charsobj != Py_None) {
592+
if(!PyUnicode_Check(charsobj))
593+
return _bad_argument_type(charsobj);
594+
chars = PyUnicode_AsUTF8(charsobj);
595+
}
596+
597+
const char *start = CSTRING_VALUE(self);
598+
while(strchr(chars, *start))
599+
++start;
600+
601+
const char *end = &CSTRING_LAST_BYTE(self) - 1;
602+
while(strchr(chars, *end))
603+
--end;
604+
605+
Py_ssize_t newsize = end - start + 1;
606+
607+
return _cstring_new(Py_TYPE(self), start, newsize);
608+
}
609+
583610
PyDoc_STRVAR(endswith__doc__, "");
584611
PyObject *cstring_endswith(PyObject *self, PyObject *args) {
585612
struct _substr_params params;
@@ -680,7 +707,7 @@ static PyMethodDef cstring_methods[] = {
680707
/* TODO: split */
681708
/* TODO: splitlines */
682709
{"startswith", cstring_startswith, METH_VARARGS, startswith__doc__},
683-
/* TODO: strip */
710+
{"strip", cstring_strip, METH_VARARGS, strip__doc__},
684711
{"swapcase", cstring_swapcase, METH_NOARGS, swapcase__doc__},
685712
/* TODO: title */
686713
/* TODO: translate */

test/test_methods.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,21 @@ def test_rindex_missing():
190190
return target.rindex('lo', 0, 4)
191191

192192

193+
def test_strip_noargs():
194+
target = cstring('\r\n\n\n\t hello, world \t\r\n\n ')
195+
assert target.strip() == cstring('hello, world')
196+
197+
198+
def test_strip_None():
199+
target = cstring('\r\n\n\n\t hello, world \t\r\n\n ')
200+
assert target.strip(None) == cstring('hello, world')
201+
202+
203+
def test_strip_arg():
204+
target = cstring('hello, world')
205+
assert target.strip('held') == cstring('o, wor')
206+
207+
193208
def test_startswith():
194209
target = cstring('hello, world')
195210
assert target.startswith('hello,') is True

0 commit comments

Comments
 (0)