如何在数组中添加字符数量?

How to add character amounts in an array?

所以我有一个字符串数组,需要获取每个字符串中的字符数并将它们加在一起得到 1 个总数。我该怎么做呢?

这是数组:

public class Final21 {
   public static String getLongString(String[] array) {

      String[] names = {"bob", "maxwell", "charley", "tomtomjack"};

   }
}

我不是添加索引,而是添加每个字符串中的字符数。 示例:bob 有 3 个字符,tomtomjack 有 10 个字符,如果将它们相加则为 13

尝试次数:

       public static int countAllLetters(String[] array) {

      String[] names = {"bob", "maxwell", "charley", "tomtomjack"};                

         int sum = 0;
         for(String s : array)
            sum += s.length();
               return sum;

      int amountOfLetters = countAllLetters(names);
         System.out.println(amountOfLetters);

   }

给出错误:

Final21.java:62: error: unreachable statement
      int amountOfLetters = countAllLetters(names);
          ^
Final21.java:65: error: missing return statement
   }
   ^
2 errors

使用流API,可以按如下方式完成:

 int sum = Arrays.stream(names)
                .mapToInt(String::length)
                .sum();

对于 Java 8+ 解决方案,请参阅

在评论中,你说你不能使用 Java 8。这个答案公开了一个针对 pre-Java 8 环境的解决方案。


如果你想 return 一个 int 包含数组中每个 String 字符的总和,你需要改变你的 return 类型方法。

public static int countAllLetters(String[] array)

请注意我如何更改名称以更好地表达此方法的行为。

要实现它,只需遍历 array 并将每个 String:

length() 加在一起
public static int countAllLetters(String[] array) {
    int sum = 0;
    for(String s : array)
        sum += s.length();
    return sum;
}

这将用作:

public static void main(String[] args) {
    String[] names = { "bob", "maxwell", "charley", "tomtomjack" };
    int amountOfLetters = countAllLetters(names);

    System.out.println(amountOfLetters);
}

所以你的最终结果是:

public class YourClass {
    public static void main(String[] args) {
        String[] names = { "bob", "maxwell", "charley", "tomtomjack" };
        int amountOfLetters = countAllLetters(names);

        System.out.println(amountOfLetters);
    }

    public static int countAllLetters(String[] array) {
        int sum = 0;
        for(String s : array)
            sum += s.length();
        return sum;
    }
}

Click here to test using an online compiler

另请注意,我没有在方法中声明 names 数组。相反,我在数组外声明它,然后将它作为参数传递给方法。这允许该方法可重复用于不同的数组,而不是单个硬编码的 names 数组。


但是,如果您想要 return 数组内容的 String 组合(基于您在问题中显示的名称和 return 类型),您需要将方法的 return 类型保持为 String,并连接数组中的项目:

public static String concat(String[] array) {
    StringBuilder builder = new StringBuilder();
    for(String s : array)
        builder.append(s);
    return builder.toString();
}