Menu
CoddyTech

遍历字符串

本课属于 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

当你需要分析文本、统计特定字符或逐个字符转换字符串时,这些方法会很有用。

challenge icon

挑战

简单

读取一行输入,其中包含一个字符串(例如,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 的格式打印字符总数
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

基础知识中的所有课

自己练习: Ruby 在线编译器