/***********************************************************
@Execise:
拉丁猪文字游戏:
将一个英语单词的第一个辅音音素的字母移动到词尾并且加上后缀-ay
@notice:
1. Swift 3.0+ 将字符串截取函数 substring 移到 Foundation 中
因此需事先引入 Foundation
2. 网上看到各种语言的实现版本,有Java的,C语系的,无论如何,
Python 的实现看上去最简洁
***********************************************************/
import Foundation
// 元音、半元音集合,除元音半元音之外的就是辅音
let vowels: Set<Character> = ["a", "e", "i", "o", "u", "y", "w"]
// 拉丁猪游戏逻辑实现
func doLatinPigGameLogic(_ string: String) {
var pos = -1, index=0
for c in string.characters {
let s = String(c).lowercased()
if !vowels.contains(Character(s)) {
pos = index
break
}
index += 1
}
if pos >= 0 {
let target = string.index(string.startIndex, offsetBy:pos)
let from = string.index(string.startIndex, offsetBy:pos+1)
let letter = String(string[target])
let front = string.substring(to: target)
let back = string.substring(from: from)
let latin = front + back + "-" + letter + "ay"
print("原文:\(string), 拉丁猪:\(latin)")
}
else{
print("[\(string)]无法转换为拉丁猪")
}
}
// 测试
doLatinPigGameLogic("Banana")
doLatinPigGameLogic("swift")
// 输出
// 原文:Banana, 拉丁猪:anana-Bay
// 原文:swift, 拉丁猪:wift-say
文末附上Python的实现版本:
# encoding=utf-8
VOWEL = ('a','e','i','o','u', 'w', 'y')
def doLatinPigGameLogic(string):
target = -1
for i, e in enumerate(string):
if e not in VOWEL:
target = i
break
if target >= 0:
front = string[0:target]
back = string[target+1:]
middle = string[target:target+1]
result = front + back + '-' + middle + 'ay'
print(u"原文:%s, 拉丁猪:%s" % (string, result))
else:
print(string + "无法转换为拉丁猪")
doLatinPigGameLogic("Banana")
doLatinPigGameLogic("swift")
// 输出
// 原文:Banana, 拉丁猪:anana-Bay
// 原文:swift, 拉丁猪:wift-say