Home » Ruby programming » Ruby programs

Ruby program to find number of characters in a string (string length)

String length in Ruby: Here, we are going to learn how to find the total number of characters (length of the string) in Ruby programming language?
Submitted by Hrithik Chandra Prasad, on August 07, 2019

Finding string length

Given a string and we have to find the total number of characters (string length) in Ruby.

There are predefined methods available in Ruby specifically for finding the number of characters in a string. They are namely .size and .length. You can use any of them for tackling the problem. But it is preferred to understand code from scratch to understand the internal logic of the code.

Methods used:

  • puts: Used to print some message on the screen for the user.
  • gets: Used to take input from the user.
  • .length: The prime functionality of this method is to find the length of the string.
  • .size: The functionality is same as .length.

Variables used:

  • str1: Used to store the string inputted by the user.
  • count: Working as a counter variable.

Ruby code to find the number of characters in a string

=begin 
Ruby program to find number of characters in the string.
=end

puts "Enter the String:"
str1=gets.chomp

count=0
for i in 1..str1.length
	if (str1[i] != '')
	count+=1
	end
end

puts "Number of characters are #{count}"

Output

RUN 1 :
Enter the String:
hrithik
Number of characters are 7

RUN 2:
Enter the String:
Includehelp.com
Number of characters are 15

Finding string length using ".length" and ".size" methods

=begin 
Ruby program to find length of a string.
=end

puts "Enter the String:"
str1=gets.chomp

puts "Number of characters are #{str1.size} using .size method"
puts "Number of characters are #{str1.length} using .length method"

Output

Enter the String:
Includehelp.com
Number of characters are 15 using .size method
Number of characters are 15 using .length method


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.