Commit 08a28634 authored by Xavier Thompson's avatar Xavier Thompson

Add strings.pyx demo

parent b1628e1e
from stdlib.string cimport Str
from libcythonplus.dict cimport cypdict
from libcythonplus.list cimport cyplist
from libc.stdio cimport puts, printf
import traceback
def test_hash():
with nogil:
s = Str('hello')
h = s.__hash__()
printf("hash('hello') = %lu\n", h)
d = cypdict[Str, int]()
d[Str('one')] = 1
d[Str('two')] = 2
one = d[Str('one')]
printf("one: %d\n", one)
def test_split():
with nogil:
s = Str("Split this sentence . ")
words = s.split()
for w in words:
puts(Str.to_c_str(w))
spaced = s.split(Str(' '))
for w in spaced:
puts(Str.to_c_str(w))
def test_join():
with nogil:
delimiter = Str(", ")
elements = cyplist[Str]()
elements.append(Str("one"))
elements.append(Str("two"))
elements.append(Str("three"))
elements.append(Str("four"))
joined = delimiter.join(elements)
puts(Str.to_c_str(joined))
def test_conversions():
with nogil:
number = Str('42')
integer = <int> number
printf('%s -> %d\n', Str.to_c_str(number), integer)
upper = Str('Hello-World')
lower = upper.lower()
printf("%s -> %s\n", Str.to_c_str(upper), Str.to_c_str(lower))
word = Str('word')
# C++ exception not handled if conversion operator is called implicitly
# fail = <int> word
fail = word.__int__()
def main():
for f in (test_split, test_join, test_hash, test_conversions):
print(">>> %s()" % f.__name__)
try:
f()
except Exception:
traceback.print_exc()
main()
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment