[英]How to print the same char n times in Haskell
I would like to print a char underlining a String n times, with n the length of the String in Haskell.我想打印一个字符下划线 n 次,n 是 Haskell 中字符串的长度。
How should I do this?我该怎么做?
My String is: "Available Chars (x)" and I want to have a char underlining that sentence, which should have exactly the same length as the "Available Chars (x)".我的字符串是:“Available Chars (x)”,我想在那个句子下划一个字符,它的长度应该与“Available Chars (x)”完全相同。 But x is an int, so it could be "1" or "10" or "1000" etc.. so the length is variable.
但 x 是一个整数,所以它可以是“1”或“10”或“1000”等。所以长度是可变的。 I got the length but i didnt know how to print that char as long as the string is...
我得到了长度,但我不知道如何打印该字符,只要字符串是...
underline :: String -> String
underline = flip replicate '-' . length
This will give you a string which is n times the character '-' where n is the length of the input string.这将为您提供一个字符串,它是字符 '-' 的 n 倍,其中 n 是输入字符串的长度。 It is the same as:
它与以下内容相同:
underline = map (const '-')
You can then use it like this (if for example yourString = "Available Chars (111)"
):然后您可以像这样使用它(例如,如果
yourString = "Available Chars (111)"
):
> putStrLn yourString >> putStrLn (underline yourString)
Available Chars (111)
---------------------
got it!知道了!
replicate n 'charHere'
for example, if you want to repeat the char '-'
12 times:例如,如果要重复字符
'-'
12 次:
replicate 12 '-'
A possibility is to (re)implement replicate
, for instance as follows,一种可能性是(重新)实现
replicate
,例如如下,
replicate' :: Int -> a -> [a]
replicate' n x = if (n <= 0) then [] else (x : replicate (n-1) x)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.