As part of learning Ruby, we will challenge "competitive programming (competitive professional)". We will output what we have learned in the learning for that purpose. This time from the second question (Triple Dots) of "At Coder Beginners Contest 168". https://atcoder.jp/contests/abc168/tasks/abc168_b
I will introduce my answer this time and the method and notation used for the answer.
There is a string S consisting of lowercase letters. If the length of S is K or less, S is output as it is. If the length of S exceeds K, cut out only the K character from the beginning and add "..." to the end to output.
Constraint ・ K is an integer between 1 and 100 ・ S is a character string consisting of lowercase letters ・ The length of S is 1 or more and 100 or less.
The input is given in the following form.
K
S
Input example
7
nikoandsolstice
Output example
#In the case of the above example
=> nikoand...
First is the code I wrote first.
k = gets.to_i
s = gets.chomp
print s.length > k ? "#{s[0...k]}..." : s
This is the first answer to the challenge of Atcoder using the ternary operator that I learned in the early days. Learning Ruby with AtCoder Beginners Selection [Product] Learn from various solutions Calculate the length of the string with the length method, compare it with K, and compare it with K. If it is larger than K, it is output by adding "..." using expression expansion, and if it is less than K, it is output as it is.
Then, the method and notation used this time are summarized below.
Returns the length of the string.
#Example
print "test".length
=> 4
By the way, the length method of the Array class returns the number of elements.
Returns the range between the start position (first) and the end position (end) of the character string as a character string. The position can be specified in the form of "0" before the first character and "1" between the first and second characters.
a = "test"
#Position specification method (image)
0 t 1 e 2 s 3 t 4
#Example
print a[0...3]
=> tes
#Returns between 0 and 3 as a string in the above positioning method
By the way, if you specify it in the form of [1, 3], 3 characters will be returned from the position of "1".
a = "test"
#Example
print a[1, 3]
=> est
Use this when you want to specify the end position in the form of the number of characters from the start position instead of specifying the position.
So far, I have introduced the methods learned from the second question (Triple Dots) of "AtCoder Beginners Contest 168".
If you have any mistakes, I would be grateful if you could point them out.
Recommended Posts