[英]How to compare a character with the next one in the same string
I am struggling a bit on how to operate with strings.我在如何操作字符串方面有点挣扎。 Furthermore, apparently there is no "while" loops, there are only "for" loops, which doesn't allow me to achieve what I want.此外,显然没有“while”循环,只有“for”循环,这不允许我实现我想要的。 Basically, given the string: "helloujjkk" I want to compare all characters with the next one, and to verify if they match.基本上,给定字符串:“helloujjkk”,我想将所有字符与下一个字符进行比较,并验证它们是否匹配。 Example, for "helloujjkk", I want to return "l","j", and "k" because those characters are followed by the same character.例如,对于“helloujjkk”,我想返回“l”、“j”和“k”,因为这些字符后跟相同的字符。 The way I did this in Python was like this:我在 Python 中这样做的方式是这样的:
hello="helloujjkk"
i=0
while i < len(hello)-1:
if hello[i] == hello[i+1]:
print hello[i]
i +=1
So far, this is the way I am iterating over the string:到目前为止,这是我遍历字符串的方式:
word := "helloujjkk"
for _,character := range word {
fmt.Println(string(character))
}
but I haven't found how can I find the "next" character in the string.但我还没有找到如何在字符串中找到“下一个”字符。
You can do the same thing you did in Python:你可以做你在 Python 中做的同样的事情:
word := "helloujjkk"
for i:=0;i<len(word)-1;i++ {
if word[i]==word[i+1] {
fmt.Println(string(word[i]))
}
}
However, this will break if your word contains multibyte characters.但是,如果您的单词包含多字节字符,这将中断。 String indexing in Go treats the string as an array of bytes, so word[i]
is the i'th byte of the string. Go 中的字符串索引将字符串视为字节数组,因此word[i]
是字符串的第 i 个字节。 This is not necessarily the i'th character.这不一定是第 i 个字符。
A better solution would be to keep the last character read from the string:更好的解决方案是保留从字符串中读取的最后一个字符:
var last rune
for i,c:=range word {
if i>0 && c==last {
fmt.Println(string(c))
}
last=c
}
}
A range over a string will iterate the runes of the string, not the bytes.字符串上的范围将迭代字符串的符文,而不是字节。 So this version is correct even if the string contains multibyte characters.所以即使字符串包含多字节字符,这个版本也是正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.