遍历字符串
本课属于 Coddy Ruby 学习旅程的“基础知识”单元。第 67 课,共 88 课。
和数组一样,Ruby 中的字符串也可以逐个字符进行迭代。each_char 方法可以让你逐个处理字符串中的每个字符。
它的工作原理如下:
word = "Ruby"
word.each_char do |char|
puts char
end这会将每个字符分别输出到一行:R、u、b、y。块变量 char 会在迭代器遍历字符串时,每次保存一个字符。
如果你既需要字符,也需要它的位置,可以使用 each_char.with_index:
word = "Hi"
word.each_char.with_index do |char, index|
puts "#{index}: #{char}"
end输出结果为:
0: H
1: i另一个实用的方法是 chars,它可以将字符串转换为由字符组成的数组。这样你就可以使用已经学过的所有数组方法:
letters = "abc".chars
puts letters # 输出:a, b, c当你需要分析文本、统计特定字符或逐个字符转换字符串时,这些方法会很有用。
挑战
简单读取一行输入,其中包含一个字符串(例如,hello)。
使用 each_char.with_index 遍历字符串,并打印每个字符及其位置。每行都应遵循以下格式:Position 0: h
打印完所有字符及其位置后,另起一行打印字符串中的字符总数,格式如下:Total characters: 5
例如,如果输入是 hello,输出应为:
Position 0: h
Position 1: e
Position 2: l
Position 3: l
Position 4: o
Total characters: 5如果输入是 Ruby,输出应为:
Position 0: R
Position 1: u
Position 2: b
Position 3: y
Total characters: 4如果输入是 code,输出应为:
Position 0: c
Position 1: o
Position 2: d
Position 3: e
Total characters: 4如果输入是 A,输出应为:
Position 0: A
Total characters: 1亲手试试
# 读取输入
str = gets.chomp
# TODO: 在下方编写你的代码
# 使用 each_char.with_index 遍历字符串
# 按 Position X: char 格式输出每个字符及其位置
# 按 Total characters: X 格式输出字符总数这节课包含一个小测验。开始学习即可作答,并记录你的进度。
基础知识中的所有课
自己练习: Ruby 在线编译器