Conoscere il numero di occorrenze in una stringa con la funzione esterna PyUnicode Count() della libreria libpython3

Da Gambas-it.org - Wikipedia.

La libreria libpython3 è un interfaccia in C di funzioni appartenenti alle risorse di Python.

La funzione "PyUnicode_Count()" consente di sapere quante volte una sub-stringa ricorre all'interno di una stringa.

Per poter fruire in Gambas di tale funzione esterna, è necessario richiamare la libreria condivisa: "libpython3.8.so.1.0 "

Mostriamo un semplice esempio pratico:

Library "libpython3.8:1.0"

' (PyObject*) PyUnicode_FromString(const char *u)
' Create a Unicode object from an UTF-8 encoded null-terminated char buffer u.
Private Extern PyUnicode_FromString(u As String) As Pointer

' (Py_ssize_t) PyUnicode_Count(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end)
' Count the number of occurrences of substr in str[start:end].
Private Extern PyUnicode_Count(strp As Pointer, substr As Pointer, start As Long, endl As Long) As Long


Public Sub Main()

 Dim p, su As Pointer
 Dim s As String
 Dim i As Integer

 s = "testo testo abcde testo testo"

 p = PyUnicode_FromString(s)
 If p == 0 Then Error.Raise("Errore !")

 su = PyUnicode_FromString("st")
 If su == 0 Then Error.Raise("Errore !")

 i = PyUnicode_Count(p, su, 0, String.Len(s))
 Print i

End


Riferimenti