oxxi
oxxi

Reputation: 472

How to add two string array members into one string variable

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.

Upvotes: 0

Views: 611

Answers (2)

vijay
vijay

Reputation: 2694

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!");  
}

Upvotes: 1

Michael Hall
Michael Hall

Reputation: 185

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

will work.

Upvotes: 3

Related Questions