Using methods for each element of the array

I have a string array that populates dynamically .... I would like to run this function:

String[] name = request.getParameterValues("name");
myString = name.substring(0, name.length() - 2);  

Now I know that this will not work, because the substring and length methods are not used for the whole array. Since I do not know how many elements will be in this array in any given period of time, do I still need to run the substring / length function for each element in this array?

+3
source share
3 answers

Yes, use an lengtharray field name. Like this:

for (int i = 0; i < name.length; ++i)
{
    String s = name[i];
    String sbtr = s.substring(0, s.length() - 2);
}

Or a better approach would be this:

for (String s: name)
{
    String sbtr = s.substring(0, s.length() - 2);
}
+6
source

Modern versions of Java (e.g. Java 5 and later) have special syntax forfor arrays (and iterations):

String[] name = request.getParameterValues("name");
for (String s: name) {
    String myString = s.substring(0, s.length() - 2);  
}
+4
source

for. . :

String[] names = request.getParameterValues("name");

for (int i=0; i<names.length; i++)
{
    String name = names[i];
    String myString = name.substring(0, name.length() - 2);
}

Or you can use "enhanced for" (also called "for everyone", it's just syntactic sugar):

String[] names = request.getParameterValues("name");

for (String name : names)
{
    String myString = name.substring(0, name.length() - 2);
}
+2
source

All Articles