Weird string case
題目:
Write a function toWeirdCase (weirdcase in Ruby)
that accepts a string, and returns the same string with all even indexed characters in each word upper cased, and all odd indexed characters in each word lower cased. The indexing just explained is zero based, so the zero-ith index is even, therefore that character should be upper cased.
The passed in string will only consist of alphabetical characters and spaces(' ')
. Spaces will only be present if there are multiple words. Words will be separated by a single space(' ')
.
Examples:
weirdcase( "String" )#=> returns "StRiNg"
weirdcase( "Weird string case" );#=> returns "WeIrD StRiNg CaSe"
思路:
先把句子拆成很多字 再把所有的字奇數字母大寫,偶數字母小寫 最後再串起來,字和字中間要加上空格
使用到的語法:
split:把字串拆開 join:把字串連起來
程式碼:
def weirdcase(string)
words = string.split(" ")
words.each do |word|
for i in 0..word.size-1
if i.even?
word[i] = word[i].upcase
else
word[i] = word[i].downcase
end
end
end
return words.join(" ")
end