使用golang检查字符串中的元音字母或数字。

huangapple go评论79阅读模式
英文:

check for vowels or numbers in a string using golang

问题

package main

import "fmt"

type groupChars []rune

func isVowel(c rune) bool {
vowels := groupChars{'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
for _, value := range vowels {
if value == c {
return true
}
}
return false
}

func main() {
myString := "OLapOKA3EOR"
t := 0
for _, value := range myString {
if isVowel(value) {
fmt.Printf("%c is Vowel\n", value)
t++
}
}
fmt.Printf("%d Vowels.", t)

}

英文:

I want know a best way to check if some char is vowel, and find a pattern to know how check for numbers too, this is my first attempt...http://play.golang.org/p/wI8pYV3BqO

package main

import "fmt"

type groupChars []rune

func isVowel(c rune) bool {
	vowels := groupChars{'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
	for _, value := range vowels {
		if value == c {
			return true
		}
	}
	return false
}

func main() {
	myString := "OLapOKA3EOR"
	t := 0
	for _, value := range myString {
		if isVowel(value) {
			fmt.Printf("%c is Vowel\n", value)
			t++
		}
	}
	fmt.Printf("%d Vowels.", t)

}

Thanks

答案1

得分: 7

我认为你想要这样的代码:

for _, value := range myString {
	switch value {
	case 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U':
		t++
	}
}

http://play.golang.org/p/MFboCiikYW

对于数字,你可以这样做:

for _, value := range myString {
	switch {
	case value >= '0' && value <= '9':
		t++
	}
}

http://play.golang.org/p/I4CbuHEVVH

英文:

I think you want something like this:

for _, value := range myString {
	switch value {
	case &#39;a&#39;, &#39;e&#39;, &#39;i&#39;, &#39;o&#39;, &#39;u&#39;, &#39;A&#39;, &#39;E&#39;, &#39;I&#39;, &#39;O&#39;, &#39;U&#39;:
		t++
	}
}

http://play.golang.org/p/MFboCiikYW

For numbers you could do:

for _, value := range myString {
	switch {
	case value &gt;= &#39;0&#39; &amp;&amp; value &lt;= &#39;9&#39;:
		t++
	}
}

http://play.golang.org/p/I4CbuHEVVH

huangapple
  • 本文由 发表于 2013年7月12日 04:25:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/17602811.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定