如何用数字替换元音字母

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

How to replace vowels with number

问题

在Go语言中,有没有一种方法可以搜索字符串中的元音字母,并用数字替换它们?程序应该随机替换元音字母,并显示格式化后的字符串。

package main

import (
	"fmt"
	"strings"
	"math/rand"
	"time"
)

func main() {
	vowels := map[rune]rune{
		'a': '3',
		'e': '2',
		'i': '1',
		'o': '4',
		'u': '5',
	}

	var s string
	fmt.Print("Enter a string: ")
	fmt.Scanln(&s)

	rand.Seed(time.Now().UnixNano())
	s = strings.Map(func(r rune) rune {
		if u, ok := vowels[r]; ok {
			return u
		}
		return r
	}, s)

	fmt.Println(s)
}

但是它仍然没有打印出随机字符串,请提供建议。

英文:

Is there any way in Go to search for vowels and replace it with numbers in a given string? the program should randomly replace the vowels with numbers and display the formatted string

package main

import (
"fmt"
"strings"
)

func main() {

vowels := map[rune]rune{
'a': '3',
'e': '2',
'i': '1',	
}

var s string
s = strings.Map(func(r rune) rune {
if u, ok := vowels[r]; ok {
    return u
}
return r
}, s)
fmt.Println(s)
}

but still it is not printing the random strings .. please suggest

答案1

得分: 8

我建议使用strings.Map来实现这个功能:

s = strings.Map(func(r rune) rune {
   switch r {
     case 'a':
       return '3'
     case 'e':
       return '2'
     // 等等
     default:
       return r
   }
}, s)

如果需要动态设置替换值,可以稍作修改,将元音字母存储在一个映射中。例如:

vowels := map[rune]rune{
    'a': '3',
    'e': '2',
}

s = strings.Map(func(r rune) rune {
    if u, ok := vowels[r]; ok {
        return u
    }
    return r
}, s)
英文:

I would suggest using strings.Map for this:

s = strings.Map(func(r rune) rune {
   switch r {
     case 'a':
       return '3'
     case 'e':
       return '2'
     // etc.
     default:
       return r
   }
}, s)

https://play.golang.org/p/D66J5hZsNs

With a slight modification, if you need to dynamically set the replacement values, you could store the vowels in a map. For example:

vowels := map[rune]rune{
	'a': '3',
	'e': '2',
}

s = strings.Map(func(r rune) rune {
	if u, ok := vowels[r]; ok {
		return u
	}
	return r
}, s)

huangapple
  • 本文由 发表于 2017年8月23日 02:39:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/45824738.html
匿名

发表评论

匿名网友

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

确定