Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

string - Count the words of an array in java

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...