Getting the Length of a String and the Size of a List

Keeping with the theme of working with Strings, there are many times when you need to know the length of that string. For example, when using substring, you want to know how many characters are in the text you just read from the site. Of you want to make sure the text actually has a length or else there is nothing to act upon.

For example, take this small snippet of code:

String address=”1650 E WASHINGTON AVE, NORTH LITTLE ROCK, AR 72114″

println(address.length())

The result would be 50 as there are 50 characters in the line. The length includes the commas.

This could be used to verify the length of a state abbreviation is 2 characters. It could also be used to verify a phone number is 10 digits or that a name is less than 25 characters, such as:

if (address.length()==0)

if (address.length()<2)

In conjunction with the length of a string, it’s possible to get the size of a list. In Groovy, a List is the same as a one dimensional array. A simple List can be set up as:

months=[‘January’, ‘February’, ‘March’, ‘April’, ‘May’, ‘June’, ‘July’, ‘August’, ‘September’, ‘October’, ‘November’, ‘December’]

The variable “months” is the name of my List and it has multiple elements. Each element is within single quotes and separated by a comma. The List also contains an opening and closing bracket.

Another familiar type of List would be state abbreviations. A List of states would be:

states=[‘AL’,’AK’,’AZ’,’AR’,’CA’,’CO’,’CT’,’DE’,’FL’,’GA’,’HI’,

‘ID’,’IL’,’IN’,’IA’,’KS’,’KY’,’LA’,’ME’,’MD’,’MA’,’MI’,’MN’,’MS’,

‘MO’,’MT’,’NE’,’NV’,’NH’,’NJ’,’NM’,’NY’,’NC’,’ND’,’OH’,’OK’,’OR’,

‘PA’,’RI’,’SC’,’SD’,’TN’,’TX’,’UT’,’VT’,’VA’,’WA’,’WV’,’WI’,’WY’]

Although these are static Lists, we can still get the size. The following command can return how many elements are within each list.

println(months.size()) – Would return 12.

println(states.size()) – Would return 50.

Building on this theme, we could then create a list of cities:

cities=[‘Dentsville’,’Woodcreek’,’Las Lomitas’,’Kings Park’,’Willisville’]

And then street names:

streetName=[‘James Kaur’,’Grace Burns’,’Alfie Robertson’,’Harry Wilson’]

And keep going until we created the building blocks to generate a random contact name. This was done within my code to create a random user including name, address, city, state, zip, phone number, email address and company. The length of each list is different, but using the .size() method, I can generate a random number and pick an element from the list.

For example, to pick a random streetName:

number=Math.abs(new Random().nextInt(streetName.size()))

customerStreetName=streetName[number]

The idea would repeat for setting up all the other parts of the customer data.

Other articles of interest:

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Comments