作者:看那个码农
公众号:看那个码农
上期内容介绍了Go语言学习之创建Goroutine|Go主题月
- Goroutine的定义
- Goroutine的创建
- 理解并发与并行
- Goroutine的拓展
本篇内容将继续带领大家走进Go语言的世界。
1.本文简介
Go语言学习之力扣-替换空格
2.题目描述
请实现一个函数,把字符串s中的每个空格替换成"%20"。
示例:
输入:s = "We are happy."
输出:"We%20are%20happy."
限制:
- 0 <= s 的长度 <= 10000
3.思路与方法
由题意可得,这道题我的方法与思路是:
- 重新创建一个
空的字符串newstr,利用for循环遍历原字符串s的字符 - 当遍历的字符
v为空格的时候,newstr+=%20 - 当遍历的字符
v不为空格的时候,newstr+=v - 最后
输出newstr即可。
4.代码实现如下
具体实现代码如下:
package main
import (
"fmt"
)
func replaceSpace(s string) string {
newstr:=""
for _,v := range s{
if string(v)==" "{
newstr+="%20"
}else{
newstr+=string(v)
}
}
return newstr
}
func main() {
str:="Hello World"
fmt.Printf("原输出:%v\n",str)
fmt.Printf("替换空格后的输出:%v\n",replaceSpace(str))
}
输出为:
5.规律总结
当然这道题还有一种更简单的方法:
调用strings包的函数replace()
该函数的用法为:
func Replace(s, old, new string, n int) string
返回将s中前n个不重叠old子串都替换为new的新字符串,如果n<0会替换所有old子串。
我们利用这种思路,用代码表示此题为:
package main
import (
"fmt"
"strings"
)
func replaceSpace(s string) string {
return strings.Replace(s," ","%20",-1)
}
func main() {
str:="Hello World"
fmt.Printf("原输出:%v\n",str)
fmt.Printf("替换空格后的输出:%v\n",replaceSpace(str))
}
输出为:
从上述解法中我们可以看到,解决需求的途径可以从多方面来思考,或是算法,也或是包所内置的函数。
我们可以根据题意,合理使用Go语言很多包所内置的函数来解决问题。
如果你觉得这篇内容对你有帮助的话:
1、点赞支持下吧,让更多的人也能看到这篇内容
2、关注公众号:看那个码农,我们一起学习一起进步。