Skip to content

Commit 7f901e4

Browse files
committed
Add string formatting exercise
1 parent a0eab8e commit 7f901e4

4 files changed

Lines changed: 69 additions & 0 deletions

File tree

internal/exercises/catalog.yaml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,11 @@ concepts:
159159
test_regex: ".*"
160160
hints:
161161
- Use `slices.Sort` to sort slices.
162+
- slug: 33_string_formatting
163+
title: String Formatting
164+
test_regex: ".*"
165+
hints:
166+
- Format strings accordingly using `%s`, `%d`, and `%f`.
162167

163168
projects:
164169
- slug: 101_text_analyzer
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package string_formatting
2+
3+
import "fmt"
4+
5+
func FormatName() string {
6+
return fmt.Sprintf("Name: %s", "\"John\"")
7+
}
8+
9+
func FormatAge() string {
10+
return fmt.Sprintf("Age: %d", 17)
11+
}
12+
13+
func FormatGpa() string {
14+
return fmt.Sprintf("GPA: %.2f", 3.75)
15+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package string_formatting
2+
3+
import "fmt"
4+
5+
func FormatName() string {
6+
return fmt.Sprintf("Name: ", "\"John\"")
7+
}
8+
9+
func FormatAge() string {
10+
return fmt.Sprintf("Age: ", 17)
11+
}
12+
13+
func FormatGpa() string {
14+
return fmt.Sprintf("GPA: ", 3.75)
15+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package string_formatting
2+
3+
import (
4+
"testing"
5+
)
6+
7+
func TestStringFormats(t *testing.T) {
8+
t.Run("Name should be formatted as a string!", func(t *testing.T) {
9+
got := FormatName()
10+
want := "Name: \"John\""
11+
12+
if got != want {
13+
t.Errorf("Expected %q, got %q", want, got)
14+
}
15+
})
16+
17+
t.Run("Age should formatted as a digit!", func(t *testing.T) {
18+
got := FormatAge()
19+
want := "Age: 17"
20+
21+
if got != want {
22+
t.Errorf("Expected %q got %q", want, got)
23+
}
24+
})
25+
26+
t.Run("GPA should be formatted for floating point number with 2 decimal places!", func(t *testing.T) {
27+
got := FormatGpa()
28+
want := "GPA: 3.75"
29+
30+
if got != want {
31+
t.Errorf("Expected %q got %q", want, got)
32+
}
33+
})
34+
}

0 commit comments

Comments
 (0)