开发者

Count the words of an array in java

开发者 https://www.devze.com 2023-04-12 21:58 出处:网络
I have a list of words e.g : \"Moon\",\"开发者_运维知识库Sun\",\"Jupiter\",\"Mars\" they are all stored in an array, lets call it \"planets\"

I have a list of words e.g : "Moon","开发者_运维知识库Sun","Jupiter","Mars" they are all stored in an array, lets call it "planets"

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

How do i get the number of words that are stored in the array ?


Those planets are not stored in one String. They are stored in a String array, so there's a String for each planet. If you want to get the number of planets in the planets array, just use: planets.length.

If you want to build a new array with the first two elements of the array, you can use:

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

You might want to take a look at the Arrays Tutorial.

Take into account that there's a typo in the planets array declaration in the question. It should be:

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

If you really had the planets in one string, you could use String.split() with a separator to build an array with each of the planets, and use length to get the length of the array:

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


Just length = planets.length


The answer on the first question is: use planets.length to count the number of String's in the array.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号