Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 336cae9

Browse files
author
Openset
committed
Add: Number of Segments in a String
1 parent 091baa7 commit 336cae9

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,9 @@
11
package number_of_segments_in_a_string
2+
3+
import "regexp"
4+
5+
func countSegments(s string) int {
6+
reg := regexp.MustCompile(`\S+`)
7+
matches := reg.FindAllString(s, -1)
8+
return len(matches)
9+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,39 @@
11
package number_of_segments_in_a_string
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
input string
7+
expected int
8+
}
9+
10+
func TestCountSegments(t *testing.T) {
11+
tests := [...]caseType{
12+
{
13+
input: "Hello, my name is John",
14+
expected: 5,
15+
},
16+
{
17+
input: "",
18+
expected: 0,
19+
},
20+
{
21+
input: " ",
22+
expected: 0,
23+
},
24+
{
25+
input: " abc ",
26+
expected: 1,
27+
},
28+
{
29+
input: "love live! mu'sic forever",
30+
expected: 4,
31+
},
32+
}
33+
for _, tc := range tests {
34+
output := countSegments(tc.input)
35+
if output != tc.expected {
36+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
37+
}
38+
}
39+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /