/***********************************************************
@Execise:
拉丁豬文字游戲:
將一個英語單詞的第一個輔音音素的字母移動到詞尾并且加上后綴-ay
@notice:
1. Swift 3.0+ 將字符串截取函數(shù) substring 移到 Foundation 中
因此需事先引入 Foundation
2. 網(wǎng)上看到各種語言的實現(xiàn)版本纤掸,有Java的坷备,C語系的峦耘,無論如何龄糊,
Python 的實現(xiàn)看上去最簡潔
***********************************************************/
import Foundation
// 元音、半元音集合屉符,除元音半元音之外的就是輔音
let vowels: Set<Character> = ["a", "e", "i", "o", "u", "y", "w"]
// 拉丁豬游戲邏輯實現(xiàn)
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)]無法轉(zhuǎn)換為拉丁豬")
}
}
// 測試
doLatinPigGameLogic("Banana")
doLatinPigGameLogic("swift")
// 輸出
// 原文:Banana, 拉丁豬:anana-Bay
// 原文:swift, 拉丁豬:wift-say
文末附上Python的實現(xiàn)版本:
# 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 + "無法轉(zhuǎn)換為拉丁豬")
doLatinPigGameLogic("Banana")
doLatinPigGameLogic("swift")
// 輸出
// 原文:Banana, 拉丁豬:anana-Bay
// 原文:swift, 拉丁豬:wift-say