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 194de30

Browse files
author
Shuo
authored
Merge pull request #412 from openset/develop
Add: Reverse Words in a String
2 parents e3500ce + d542d1a commit 194de30

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,15 @@
11
package reverse_words_in_a_string
2+
3+
import (
4+
"regexp"
5+
"strings"
6+
)
7+
8+
func reverseWords(s string) string {
9+
reg := regexp.MustCompile(`\S+`)
10+
words := reg.FindAllString(s, -1)
11+
for i, j := 0, len(words)-1; i < j; i, j = i+1, j-1 {
12+
words[i], words[j] = words[j], words[i]
13+
}
14+
return strings.Join(words, " ")
15+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,31 @@
11
package reverse_words_in_a_string
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
input string
7+
expected string
8+
}
9+
10+
func TestReverseWords(t *testing.T) {
11+
tests := [...]caseType{
12+
{
13+
input: "the sky is blue",
14+
expected: "blue is sky the",
15+
},
16+
{
17+
input: " hello world! ",
18+
expected: "world! hello",
19+
},
20+
{
21+
input: "a good example",
22+
expected: "example good a",
23+
},
24+
}
25+
for _, tc := range tests {
26+
output := reverseWords(tc.input)
27+
if output != tc.expected {
28+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
29+
}
30+
}
31+
}

0 commit comments

Comments
(0)

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