Golang中如何检查最后一个斜杠前是否有字母n
Golang中如何检查最后一个斜杠前是否有字母n 你好
如何检查在最后一个 / 之前是否有一个 n
例如,如果我有 “testn/tes t/ testn”,它应该返回 false;但如果我有 “test/help n/ exemple”,它应该返回 true。
2 回复
- 反转字符串
- 找到第一个
/ - 检查下一个字符是否为
n
或者,从后向前迭代,而不是从前向后。
更多关于Golang中如何检查最后一个斜杠前是否有字母n的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
可以使用 strings.LastIndex 找到最后一个斜杠的位置,然后检查其前一个字符是否为 n:
package main
import (
"fmt"
"strings"
)
func hasNBeforeLastSlash(s string) bool {
// 找到最后一个斜杠的位置
lastSlash := strings.LastIndex(s, "/")
// 如果没有斜杠或斜杠在字符串开头,返回false
if lastSlash <= 0 {
return false
}
// 检查斜杠前一个字符是否为'n'
return s[lastSlash-1] == 'n'
}
func main() {
tests := []string{
"testn/tes t/ testn", // false
"test/help n/ exemple", // true
"example/n/test", // true
"example/test", // false
"n/", // true
"/test", // false
"test", // false
"", // false
}
for _, test := range tests {
fmt.Printf("%q -> %v\n", test, hasNBeforeLastSlash(test))
}
}
输出:
"testn/tes t/ testn" -> false
"test/help n/ exemple" -> true
"example/n/test" -> true
"example/test" -> false
"n/" -> true
"/test" -> false
"test" -> false
"" -> false
如果字符串可能包含多字节字符,可以使用 []rune 转换:
func hasNBeforeLastSlashUnicode(s string) bool {
runes := []rune(s)
lastSlash := -1
// 手动查找最后一个斜杠
for i := len(runes) - 1; i >= 0; i-- {
if runes[i] == '/' {
lastSlash = i
break
}
}
if lastSlash <= 0 {
return false
}
return runes[lastSlash-1] == 'n'
}

