且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-11-13 22:55:21

有关Java 8+解决方案,请参考Aominè的答案

For a Java 8+ solution, refer to this answer by Aominè.

在注释中,您说您不能使用Java 8。 Java 8环境。

In the comments, you say you can't use Java 8. This answer exposes a solution for pre-Java 8 environments.

如果要返回 int 包含数组中每个 String 中字符的总和,您需要更改方法的返回类型。

If you want to return an int containing the combined amount of characters from every String in the array, you need to change the return type of your method.

public static int countAllLetters(String[] array)

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

Notice how I changed the name to better express the behavior of this method.

要实现该方法,只需遍历 array 并将每个 String length()加在一起:

To implement it, simply loop through the array and add together the length() of each String:

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);
}

因此,您的最终结果将是:

So your finished result would be:

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;
    }
}

点击此处使用在线编译器进行测试

还要注意我怎么做不要在方法内部声明 names 数组。相反,我在数组外部声明了它,然后将其作为参数传递给了方法。这使得该方法可用于不同的数组,而不是单个硬编码的 names 数组。

Also notice how I don't declare the names array inside the method. Instead, I declared it outside of the array, then passed it into the method as an argument. This allows the method to be reusable for different arrays, rather than a single hard-coded names array.

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

However, if you want to return a String of array's content combined (based on the name & return type you're showing in your question), you need to keep the return type of your method as String, and concat the items from the array:

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