import stdio import t, c import string # ============================================================ # string_test - string.py 库函数测试 # # 测试 strlen / strcmp / strncmp / atoi / strchr / strstr # ============================================================ def test_strlen(): stdio.printf("--- Test 1: strlen ---\n") l1: t.CSizeT = string.strlen("Hello") stdio.printf("strlen(Hello)=%lu (expect 5)\n", l1) l2: t.CSizeT = string.strlen("") stdio.printf("strlen()=%lu (expect 0)\n", l2) l3: t.CSizeT = string.strlen("Hello, World!") stdio.printf("strlen(Hello, World!)=%lu (expect 13)\n", l3) def test_strcmp(): stdio.printf("--- Test 2: strcmp ---\n") r1: t.CInt = string.strcmp("abc", "abc") stdio.printf("strcmp(abc,abc)=%d (expect 0)\n", r1) r2: t.CInt = string.strcmp("abc", "abd") stdio.printf("strcmp(abc,abd)=%d (expect <0)\n", r2) r3: t.CInt = string.strcmp("abd", "abc") stdio.printf("strcmp(abd,abc)=%d (expect >0)\n", r3) def test_strncmp(): stdio.printf("--- Test 3: strncmp ---\n") r1: t.CInt = string.strncmp("abcdef", "abcXYZ", 3) stdio.printf("strncmp(abcdef,abcXYZ,3)=%d (expect 0)\n", r1) r2: t.CInt = string.strncmp("abcdef", "abcXYZ", 4) stdio.printf("strncmp(abcdef,abcXYZ,4)=%d (expect <0)\n", r2) def test_atoi(): stdio.printf("--- Test 4: atoi ---\n") n1: t.CInt = string.atoi("123") stdio.printf("atoi(123)=%d (expect 123)\n", n1) n2: t.CInt = string.atoi("-456") stdio.printf("atoi(-456)=%d (expect -456)\n", n2) n3: t.CInt = string.atoi(" 789") stdio.printf("atoi( 789)=%d (expect 789)\n", n3) def test_strchr(): stdio.printf("--- Test 5: strchr ---\n") # strchr 返回指向字符的指针,不为 None 表示找到 p: str = string.strchr("Hello", 108) # 'l' = 108 if p is not None: stdio.printf("strchr(Hello,'l') found, char=%d (expect 108)\n", c.Deref(p)) else: stdio.printf("strchr(Hello,'l') NOT FOUND (FAIL)\n") p2: str = string.strchr("Hello", 122) # 'z' = 122 if p2 is None: stdio.printf("strchr(Hello,'z') not found OK\n") else: stdio.printf("strchr(Hello,'z') FAIL (should be None)\n") def test_strstr(): stdio.printf("--- Test 6: strstr ---\n") p: str = string.strstr("Hello World", "World") if p is not None: stdio.printf("strstr(Hello,World) found OK\n") else: stdio.printf("strstr(Hello,World) NOT FOUND (FAIL)\n") p2: str = string.strstr("Hello World", "xyz") if p2 is None: stdio.printf("strstr(Hello,xyz) not found OK\n") else: stdio.printf("strstr(Hello,xyz) FAIL (should be None)\n") def string_test() -> int: stdio.printf("=== string_test: string.py 库函数测试 ===\n\n") test_strlen() test_strcmp() test_strncmp() test_atoi() test_strchr() test_strstr() stdio.printf("\n=== string_test 完成 ===\n") return 0