Skip to content

Instantly share code, notes, and snippets.

@JuniorPolegato
Created July 16, 2015 17:12
Show Gist options
  • Save JuniorPolegato/dc736afed8a0e8a3a7bd to your computer and use it in GitHub Desktop.
Save JuniorPolegato/dc736afed8a0e8a3a7bd to your computer and use it in GitHub Desktop.
#include <Python.h>
/* Compilando:
* gcc -Wall -shared -fPIC -o intercalar.so intercalar.c -I /usr/include/python2.7
*
* Usando:
* import intercalar
* intercalar.intercalar('AABBCCDDEE', '1', 2)
*/
static PyObject *
intercalar_intercalar(PyObject *self, PyObject *args){
PyObject* result;
char *texto, c, *intercalado, *t, *i;
int passo, pos, tam;
if (!PyArg_ParseTuple(args, "sci", &texto, &c, &passo))
return NULL;
if (passo < 1){
PyErr_SetString(PyExc_ValueError, "Passo precisa ser maior que zero!");
return NULL;
}
tam = strlen(texto);
tam = tam / passo * (passo + 1) + tam % passo + 1;
intercalado = (char*)malloc(tam);
t = texto;
i = intercalado;
pos = 0;
for (pos = 0; *t; pos++) {
*(i++) = *(t++);
if ((pos + 1) % passo == 0)
*(i++) = c;
}
*i = '\0';
result = Py_BuildValue("s", intercalado);
free(intercalado);
return result;
}
static PyMethodDef intercalar_methods[] = {
{"intercalar", intercalar_intercalar, METH_VARARGS,
"Intercala 1 caracter a cada passo.\n"
"Uso: intercalar(texto, caracter, passo)\n"
"Return: texto intercalado"},
{NULL, NULL, 0, NULL} /* Sentinela */
};
PyMODINIT_FUNC
initintercalar(void)
{
(void) Py_InitModule("intercalar", intercalar_methods);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment