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;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…