【问题标题】:Best way for mapping array of strings [closed]映射字符串数组的最佳方法[关闭]
【发布时间】:2021-08-28 10:21:21
【问题描述】:

我面临下一个任务:我有一个代表位置名称的字符串数组,例如 ["Rome", "Paris", "Kyiv", "Barcelona"],我必须在后面添加一个逗号除了最后一个元素之外的每个元素。那么,最好的方法是什么?感谢您的帮助。

【问题讨论】:

  • 到目前为止你尝试过什么?分享你的代码并解释你到底在哪里卡住了。

标签: ios arrays swift string algorithm


【解决方案1】:

你可以这样做 -

["Rome", "Paris", "Kyiv", "Barcelona"].joined(separator: ", ")

【讨论】:

    【解决方案2】:

    在真实应用中,使用

    呈现列表
    ListFormatter().string(from:)
    

    【讨论】:

      【解决方案3】:

      这是在 java 中,但想法是在第一个元素之后开始,然后在它后面添加逗号。

      if (arrayListWords.length >= 1) {
      System.out.print(arrayListWords[0]);
      }
      
      // note that i starts at 1, since we already printed the element at index 0
      for (int i = 1; i < arrayListWords.length, i++) { 
       System.out.print(", " + arrayListWords[i]);
      }
      

      【讨论】:

        猜你喜欢
        • 2020-06-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-27
        相关资源
        最近更新 更多