Skip to content

Commit 864fea7

Browse files
authored
Merge pull request #28 from misoboy/master
added function DefaultString, DefaultIfBlank
2 parents 41ac869 + 740ce87 commit 864fea7

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

stringutils.go

+16
Original file line numberDiff line numberDiff line change
@@ -222,3 +222,19 @@ func IndexOf(str string, sub string, start int) int {
222222
func IsEmpty(str string) bool {
223223
return len(str) == 0
224224
}
225+
226+
// Returns either the passed in string, or if the string is empty, the value of defaultStr.
227+
func DefaultString(str string, defaultStr string) string {
228+
if IsEmpty(str) {
229+
return defaultStr
230+
}
231+
return str
232+
}
233+
234+
// Returns either the passed in string, or if the string is whitespace, empty (""), the value of defaultStr.
235+
func DefaultIfBlank(str string, defaultStr string) string {
236+
if IsBlank(str) {
237+
return defaultStr
238+
}
239+
return str
240+
}

stringutils_test.go

+30
Original file line numberDiff line numberDiff line change
@@ -307,3 +307,33 @@ func ExampleIndexOfDifference() {
307307
// 0
308308
// 2
309309
}
310+
311+
func ExampleDefaultString() {
312+
313+
out1 := DefaultString("abc", "")
314+
out2 := DefaultString("ab", "c")
315+
out3 := DefaultString("", "abc")
316+
317+
fmt.Println(out1)
318+
fmt.Println(out2)
319+
fmt.Println(out3)
320+
// Output:
321+
// abc
322+
// ab
323+
// abc
324+
}
325+
326+
func ExampleDefaultIfBlank() {
327+
328+
out1 := DefaultIfBlank("", "abc")
329+
out2 := DefaultIfBlank(" ", "abc")
330+
out3 := DefaultIfBlank("ab", "cd")
331+
332+
fmt.Println(out1)
333+
fmt.Println(out2)
334+
fmt.Println(out3)
335+
// Output:
336+
// abc
337+
// abc
338+
// ab
339+
}

0 commit comments

Comments
 (0)