如何使用Haskell编写一个程序来计算给定字符串的字符数和单词数
发布时间:2023-12-09 20:36:28
下面是一个使用Haskell编写的程序,该程序可以计算给定字符串的字符数和单词数。程序会将输入的字符串按空格进行分割,然后计算字符数和单词数。
import Data.Char (isSpace) countCharacters :: String -> Int countCharacters = length countWords :: String -> Int countWords = length . words main :: IO () main = do putStrLn "请输入一段文本:" input <- getLine let numCharacters = countCharacters input let numWords = countWords input putStrLn $ "字符数:" ++ show numCharacters putStrLn $ "单词数:" ++ show numWords
使用例子:
输入:
请输入一段文本: Hello, world! This is a Haskell program.
输出:
字符数:34 单词数:7
输入:
请输入一段文本: This is a test.
输出:
字符数:15 单词数:4
