C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
For: We use a for-loop over the string to iterate over the chars in forward order. We access each char by its index.
While: We can use a while-loop to iterate over the string in a reverse (backwards) order. We begin at length minus one.
While, UntilRuby program that uses string length, for loop
# An input string.
value = "ABC"
# Display the string.
puts "VALUE:" << value
puts "LENGTH:" << String(value.length)
# Loop over characters in the string forwards.
for i in 0..value.length - 1
puts "CHAR FORWARD:" << value[i]
end
# Loop over characters backwards.
temp = value.length - 1
while temp >= 0
puts "CHAR BACKWARD:" <> value[temp]
temp -= 1
end
Output
VALUE:ABC
LENGTH:3
CHAR FORWARD:A
CHAR FORWARD:B
CHAR FORWARD:C
CHAR BACKWARD:C
CHAR BACKWARD:B
CHAR BACKWARD:A