Skip to content

Commit d40af23

Browse files
committed
Last word length
1 parent 3b3859f commit d40af23

File tree

3 files changed

+69
-0
lines changed

3 files changed

+69
-0
lines changed

codes/last_word_length.mojo

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
### Last word length
2+
### Return the length of the last word in a given space-separated string
3+
4+
5+
fn last_word_length(s: String) -> Int:
6+
if len(s) == 0:
7+
return 0
8+
i, length = len(s) - 1, 0
9+
while i >= 0 and s[i] == " ":
10+
i -= 1
11+
while i >= 0 and s[i] != " ":
12+
length += 1
13+
i -= 1
14+
return length
15+
16+
17+
fn main() raises:
18+
from testing import assert_true
19+
20+
result = last_word_length("Hello World")
21+
assert_true(result == 5, "Assertion failed")
22+
23+
result = last_word_length(" ")
24+
assert_true(result == 0, "Assertion failed")
25+
26+
result = last_word_length(" fly me to the moon ")
27+
assert_true(result == 4, "Assertion failed")
28+
29+
result = last_word_length("luffy is still joyboy")
30+
assert_true(result == 6, "Assertion failed")

docs/index.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,3 +60,5 @@
6060
🟢 [Check device core](cores.md) ➔ Check physical and logical cores of the device
6161

6262
🟢 [SIMD Select](simd_select.md) ➔ Select based on a SIMD (Single Instruction, Multiple Data) mask
63+
64+
🟢 [Last word length](last_word_length.md) ➔ Return the length of the last word in a given space-separated string

docs/last_word_length.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
### Last word length
2+
### Return the length of the last word in a given space-separated string
3+
4+
```python
5+
6+
7+
fn last_word_length(s: String) -> Int:
8+
if len(s) == 0:
9+
return 0
10+
i, length = len(s) - 1, 0
11+
while i >= 0 and s[i] == " ":
12+
i -= 1
13+
while i >= 0 and s[i] != " ":
14+
length += 1
15+
i -= 1
16+
return length
17+
18+
19+
fn main() raises:
20+
from testing import assert_true
21+
22+
result = last_word_length("Hello World")
23+
assert_true(result == 5, "Assertion failed")
24+
25+
result = last_word_length(" ")
26+
assert_true(result == 0, "Assertion failed")
27+
28+
result = last_word_length(" fly me to the moon ")
29+
assert_true(result == 4, "Assertion failed")
30+
31+
result = last_word_length("luffy is still joyboy")
32+
assert_true(result == 6, "Assertion failed")
33+
34+
```
35+
36+
37+
[Source](https://github.com/ratulb/mojo_programming/blob/main/codes/last_word_length.mojo)

0 commit comments

Comments
 (0)