计算 2 个字符串的长度并添加它们失败

Calculate length of 2 Strings and add them fails

我无法解决字符串长度计算问题。所以整件事都来自我正在阅读的一本关于 kotlin 编程的书:Big Nerd Ranch Guide。有一个酒馆菜单应该用代码格式化。提供的菜单列表如下所示:

shandy,Dragon's Breath,5.91
elixir,shirley temple,4.12
meal,goblet of la croix,1.22
desert dessert,pickled camel hump,7.33
elixir,iced boilermaker,11.22

此列表的格式应如下所示:

*** Welcome to Taernyl's Folly ***

Dragon's Breath...............5.91
Shirley Temple................4.12
Goblet Of La Croix............1.22
Pickled Camel Hump............7.33
Iced Boilermaker.............11.22

所以我创建了一个函数,它获取菜单数据并根据逗号将其拆分(感谢@gidds 的更正)。我不需要每一行的第一个条目。这是函数:

fun createMenuList(menuData: List<String>) {
    // print the Header with the Tavern Name
    println("*** Welcome to $TAVERN_NAME ***\n")

    // List of the parts of the beverage name since I need to capitalize each part of the name
    var nameList: List<String>

    menuData.forEachIndexed { _, menuData ->
        // the menu data is split by comma and and stored in beverageName and beveragePrice
        var (_, beverageName, beveragePrice) = menuData.split(",")

        // next line I calculate the dots I need to fill in the
        // space between the name and the price based on a line length of 34
        val dotCount = 34 - (beverageName.length + beveragePrice.length)

        // if I print the calculations for both Strings the calculation works
        // for the beverageName but not for beveragePrice, it's always 5 even though it is not
        println("Namelength:${beverageName.length} Pricelength:${beveragePrice.length}")

        var counter = 0
        var dots = ""

        // add as many dots as calculated by the string operation for the space
        while (counter <= dotCount) {
            dots += "."
            counter++
        }

        nameList = beverageName.split(' ')
        var cappedName = ""
        for (name in nameList) {
            cappedName += name.replaceFirstChar { it.uppercase() } + " "
        }
        cappedName = cappedName.substring(0 until cappedName.length - 1)
        println("$cappedName$dots$beveragePrice")

    }
}

如果我 运行 代码,饮料价格的长度总是计算为 5, 即使前 4 个条目应该是 4。 这导致前 4 个条目的行长度错误,我不知道我做错了什么。 这是我用打印的字符串长度得到的结果。有趣的是,相同的代码在 windows 机器上可以正常工作。我感谢我能得到的每一个帮助,提前致谢。

*** Welcome to Taernyl's Folly ***

Namelength:15 Pricelength:5
Dragon's Breath...............5.91
Namelength:14 Pricelength:5
Shirley Temple................4.12
Namelength:18 Pricelength:5
Goblet Of La Croix............1.22
Namelength:18 Pricelength:5
Pickled Camel Hump............7.33
Namelength:16 Pricelength:5
Iced Boilermaker..............11.22

感谢作为 Tenfour04、Henry Twist 和 gidds 在评论中回答我的问题的所有人。 Tenfour04给出了最初的正确答案。拆分后,换行符将添加到列表中的元素中。我已经在 windows 上看到它现在也发生了。 因此,我猜当您从文件中读取字符串时,应该始终将 trim() 与 split() 一起使用。 解决方案是:

var (_, beverageName, beveragePrice) = menuData.trim().split(",")