void split( const std::string & str, std::vector< std::string > & result, const std::string & sep, int maxsplit ) { result.clear(); if ( maxsplit < 0 ) maxsplit = MAX_32BIT_INT;//result.max_size(); if ( sep.size() == 0 ) { split_whitespace( str, result, maxsplit ); return; } std::string::size_type i,j, len = str.size(), n = sep.size(); i = j = 0; while ( i+n <= len ) { if ( str[i] == sep[0] && str.substr( i, n ) == sep ) { if ( maxsplit-- <= 0 ) break; result.push_back( str.substr( j, i - j ) ); i = j = i + n; } else { i++; } } result.push_back( str.substr( j, len-j ) ); }
static PyObject * strop_splitfields(PyObject *self, PyObject *args) { Py_ssize_t len, n, i, j, err; Py_ssize_t splitcount, maxsplit; char *s, *sub; PyObject *list, *item; WARN; sub = NULL; n = 0; splitcount = 0; maxsplit = 0; if (!PyArg_ParseTuple(args, "t#|z#n:split", &s, &len, &sub, &n, &maxsplit)) return NULL; if (sub == NULL) return split_whitespace(s, len, maxsplit); if (n == 0) { PyErr_SetString(PyExc_ValueError, "empty separator"); return NULL; } list = PyList_New(0); if (list == NULL) return NULL; i = j = 0; while (i+n <= len) { if (s[i] == sub[0] && (n == 1 || memcmp(s+i, sub, n) == 0)) { item = PyString_FromStringAndSize(s+j, i-j); if (item == NULL) goto fail; err = PyList_Append(list, item); Py_DECREF(item); if (err < 0) goto fail; i = j = i + n; splitcount++; if (maxsplit && (splitcount >= maxsplit)) break; } else i++; } item = PyString_FromStringAndSize(s+j, len-j); if (item == NULL) goto fail; err = PyList_Append(list, item); Py_DECREF(item); if (err < 0) goto fail; return list; fail: Py_DECREF(list); return NULL; }