You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将字符串数组大小设置为现有字符串的长度(类似int的.length)

How to Set a String Array's Size to a String's Length in Java

Hey there! I totally get the confusion when you're starting out—mixing up how we get lengths for different types can feel tricky at first. Let's break this down nice and simple.

First, let's clear up a key difference you'll run into all the time in Java:

  • For arrays, we use the length property (no parentheses, like myArray.length)
  • For String objects, we use the length() method (with parentheses, since it's a function call: myString.length())

So to create a String array whose size matches the length of your existing string, you just pass str.length() directly when initializing the array. Here's a concrete example using your "Banana" string:

public class Main {
    public static void main(String[] args) {
        String str = "Banana";
        // Create a String array with size equal to str's character count (6 here)
        String[] strArray = new String[str.length()];
        
        // To confirm it works, let's print the array's length
        System.out.println("Array length: " + strArray.length); // Outputs 6
    }
}

This works because str.length() returns the number of characters in the string (6 for "Banana"), and we use that dynamic value to set how many elements our array can hold. The best part? If you later change str to something else (like "Apple" which is 5 characters), you don't have to manually update the array size—it'll adjust automatically because we're using the length() method instead of a hardcoded number.

A quick heads-up: Make sure your str variable isn't null when you call length(), otherwise you'll get a NullPointerException. But as long as you initialize str with a valid string (like your "Banana" example), you're good to go.

内容的提问来源于stack exchange,提问作者pro5476

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:29:26