简体   繁体   中英

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. Basically, given the string: "helloujjkk" I want to compare all characters with the next one, and to verify if they match. Example, for "helloujjkk", I want to return "l","j", and "k" because those characters are followed by the same character. The way I did this in Python was like this:

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:

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. This is not necessarily the i'th character.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM