【问题标题】:Count the words of an array in java在java中计算数组的单词
【发布时间】:2011-10-13 08:06:53
【问题描述】:

我有一个单词列表,例如:“月亮”、“太阳”、“木星”、“火星”,它们都存储在一个数组中,我们称之为“行星”

String[] planets = new String[]{"Moon","Sun","Jupiter","Mars"}

如何获取存储在数组中的单词数?

【问题讨论】:

  • 其实planets是一个数组而不是字符串。能改一下吗?
  • String[] planets = 字符串数组,所以数组长度就是你的字数。
  • 是一个数组,可以这样获取数组的长度:planets.length
  • 如果您想问另一个问题,请使用另一个问题。
  • 关于行星的 OP 并没有错:太阳和月亮是最初的七颗行星中的两颗。

标签: java string


【解决方案1】:

这些行星没有存储在一个字符串中。它们存储在一个字符串数组中,因此每个行星都有一个字符串。如果要获取planets 数组中的行星数量,只需使用:planets.length

如果你想用数组的前两个元素构建一个新数组,你可以使用:

   String[] fewPlanets = new String[]{planets[0], planets[1]};

您可能想看看Arrays Tutorial

考虑到问题中的 planets 数组声明中有错字。应该是:

String[] planets = new String[]{"Moon","Sun","Jupiter","Mars"}

如果你真的把行星放在一个字符串中,你可以使用String.split()和一个分隔符来为每个行星构建一个数组,并使用length来获取数组的长度:

String planets = "Moon,Sun,Jupiter,Mars";
String[] planetsArray = planets.split(",");
int numberOfPlanets = planetsArray.length;

【讨论】:

    【解决方案2】:

    只要length = planets.length

    【讨论】:

      【解决方案3】:

      第一个问题的答案是:用planets.length统计数组中String的个数。

      【讨论】:

        猜你喜欢
        • 2021-08-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多