strings

Code

basic_string_example.odin ¶
86 linesSource

1package basic_string_example
2
3import "core:fmt"
4import "core:strings"
5
6/*
7	Strings in Odin are immutable.
8
9	Runes are unencoded code points like 0x96EA which get viewed as 雪.
10	When you construct a string with runes, they get encoded into a UTF-8 format and stored as an array of bytes.
11
12	You can think of runes as characters, but be careful, as one rune does not always equal one character.
13	For example: 👋🏻 produces 2 runes. One for the hand and one for the mask color.
14*/
15main :: proc() {
16
17	name1 := "雪"
18	name2 := "月"
19
20	// Check if the names are equal.
21	is_equal := strings.compare(name1, name2)
22
23	if is_equal == 0 {
24		fmt.println("The names match!")
25	} else {
26		fmt.println("The names do not match!")
27	}
28
29	// contains_rune will return true if the rune is present, false otherwise.
30	contains_A := strings.contains_rune(name1, 'A')
31	if contains_A {
32		fmt.println("name_1 contains the rune!")
33	} else {
34		fmt.println("name_1 does not contain the rune!")
35	}
36
37	// index will return the index of the needle, or -1 if not present
38	index_of_A := strings.index(name1, "A")
39	if index_of_A == -1 {
40		fmt.println("name_1 does not contain the needle!")
41	} else {
42		fmt.println("name_1 contains the needle and is located at index:", index_of_A)
43	}
44
45	fmt.println("name1 is", strings.rune_count(name1), "rune(s) long.")
46
47	// Join the two names together separated by a comma!
48	list_of_names := strings.join({name1, name2}, ",")
49	defer delete(list_of_names)
50	fmt.println(list_of_names)
51
52	// Split the list of names into an array of names.
53	names := strings.split(list_of_names, ",")
54	defer delete(names)
55	fmt.println(names)
56
57	// Concatenate strings.
58	new_name := strings.concatenate({name1, name2})
59	defer delete(new_name)
60	fmt.println(new_name)
61
62	FILE_CONTENTS ::
63	`README.md
64	 .gitignore
65	 chapter_1.md`
66
67	file_names := strings.split(FILE_CONTENTS, "\n")
68	defer delete(file_names)
69	file_count := len(file_names)
70	markdown_file_count: int
71
72	for line in file_names {
73		if strings.contains(line, ".md") {
74			markdown_file_count += 1
75		}
76	}
77
78	fmt.printf("There are %i files and %i of them are markdown files.\n", file_count, markdown_file_count)
79
80	// The fields proc will split the string with the separator being whitespace. Extra whitespace will be ignored.
81	command_string := "ls   Downloads"
82	command_tokens := strings.fields(command_string)
83	defer delete(command_tokens)
84	fmt.println(command_tokens)
85
86}

Declarations Used 11