0

I've been trying to figure out how to add an extra string array member to a string variable with no luck. Here is the code.

 myDirString = myDirString.trim();
    String[] myDirStringParts = myDirString.split(" +");

    MySize = myDirStringParts[0];
    MyNum =  myDirStringParts[1];
    Total =  myDirStringParts[2];
    MyName = myDirStringParts[3];

Basically I want myDirStringParts[2]; to also be included into MyName.

1
  • 3
    if you are getting an out of bounds error it means the split isn't producing 4 parts, which means there aren't 4 parts separated by " +", perhaps you should show the value of myDirString Commented Apr 20, 2013 at 2:19

2 Answers 2

3
MyName = myDirStringParts[3] + myDirStringParts[2];

will work.

Sign up to request clarification or add additional context in comments.

6 Comments

well the problem is that all the strings im passing into MyDirectory are the same except the last one. The last one is short by 1 array. Hence the out of bounds, but I'm supposed to pass the third array member from the last string to MyName. It's really tricky.
2365106332 1140 SUB-TOTAL: E:\WIS26\MYSQL
91535864328 301122 TOTAL
So like above, the last string would be 4th one, and I want "TOTAL" to be MyName as well.
if (myDirStringParts.length == 4) MyName = myDirStringParts[3]; else MyName = myDirStringParts[2];
|
1

Simply

MyName = myDirStringParts[3] + myDirStringParts[2];

should do the trick.

However, i notice a few things about your code that i would like to point out:

  1. Declare the variables MyName, Total, MyNum, MySize.
  2. Make sure that myDirStringParts contains atleast 3 elements after the split(" +") call.

You can do this by the following code snippet:

if(myDirStringParts.length >= 4) {  
    MySize = myDirStringParts[0];
    MyNum = myDirStringParts[1];
    Total = myDirStringParts[2];
    MyName = myDirStringParts[3] + myDirStringParts[2];
}  else {  
    // print out an error message.  
    System.err.println("myDirString does not contain all the required data!");  
}

1 Comment

It should be at least 4, since 3 is the 4th element, 0-indexed.

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.