如何用go语言实现:判断字符串 `s` 是否包含某个字符串前缀 `prefix` 和某个字符串后缀 `suffix`,都包含返回 true 否则 false,允许 prefix 或 suffix 其一为空,若同时为空返回 false
时间: 2024-01-25 15:04:06 浏览: 35
可以使用 strings.HasPrefix 和 strings.HasSuffix 函数来判断字符串是否包含前缀和后缀。同时,需要判断前缀和后缀是否为空,若为空则返回 false。
以下是示例代码:
```
package main
import (
"fmt"
"strings"
)
func containsPrefixAndSuffix(s, prefix, suffix string) bool {
if prefix == "" && suffix == "" {
return false
}
if prefix == "" {
return strings.HasSuffix(s, suffix)
}
if suffix == "" {
return strings.HasPrefix(s, prefix)
}
return strings.HasPrefix(s, prefix) && strings.HasSuffix(s, suffix)
}
func main() {
s := "hello world"
prefix := "he"
suffix := "ld"
fmt.Println(containsPrefixAndSuffix(s, prefix, suffix)) // true
prefix = ""
fmt.Println(containsPrefixAndSuffix(s, prefix, suffix)) // true
suffix = ""
fmt.Println(containsPrefixAndSuffix(s, prefix, suffix)) // false
prefix = "he"
suffix = "llo"
fmt.Println(containsPrefixAndSuffix(s, prefix, suffix)) // false
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)