3

I have a string array that is being filled 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 wont run, because substring and length methods aren't used for the whole array. Since i dont know how many items will be in this array at any given run time, is there anyway to run the substring/length function for every item in this array?

0

3 Answers 3

6

Yes, use you can use length field of the name array. 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);
}
Sign up to request clarification or add additional context in comments.

4 Comments

thanks, I dont run java 5, so I have to use the bottom example. thank you
Any particular reason you're using such an old version of Java? The current release is Java 6, and Java 7 Milestone 13 was released in February.
no reason....just haven't done it, I honestly didn't realize they were on Java 7.
Don't worry about Java 7 yet, it's not actually released yet. IMO, by not using at least Java 5, you're really missing out on a ton of stuff.
4

Modern versions of Java (i.e Java 5 and later) have a special for syntax for arrays (and iterables):

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

Comments

2

You'd use a for loop. There are a couple different ways to do this. The most basic way:

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 the "enhanced for" (also called a "for-each" — it's just syntactic sugar):

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.