Code Junkie
Code Junkie

Reputation: 7788

Split id and add to array

I have to split off the last two characters of an ID, the id may vary in length. example 56427R1 and R00220P3. Once the last two characters are split off, I need to add the first set of characters and the last two characters to an ArrayList. Thanks in advance.

I've tried the following

            List<String> list = new ArrayList<String>();
            list.add(clientValue.substring(0, clientValue.length()-2));

but was having trouble keeping the last 2 characters while removing the first half.

Resolved, repaired with the following code

            ArrayList<String> list = new ArrayList<String>();
            list.add(clientValue.substring(clientValue.length()-2));
            list.add(clientValue.substring(0, clientValue.length()-2));

Upvotes: 1

Views: 316

Answers (3)

Gio
Gio

Reputation: 1954

You can do it easily like this:

String myID = "56427R1";
String extractedID = myID.substring((myID.length()-2), myID.length());
ArrayList<String> list = new ArrayList<String>;v
list.add(myID.substring((myID.length()-2)));
list.add(extractedID);

UPDATE:

String myID = "56427R1";
String extractedID = myID.substring((myID.length()-2), myID.length());

char[] a = extractedID.toCharArray();
char[] b = myID.substring(myID.length()-2).toCharArray();
ArrayList<Character> list = new ArrayList<Character>();

for(int i = 0; i < b.length; i++)
list.add(b[i]);

for(int j = 0; j < a.length; j++)
list.add(a[j]);

Upvotes: 0

hmjd
hmjd

Reputation: 122001

Use String.substring() with String.length() to split the string.

Use ArrayList<String>.add() to append to an ArrayList.

EDIT:

the code you have posted is correct: clientValue is not modified by the call to clientValue.substring() but returns a new String instance. Java String are immutable. To complete your code:

List<String> list = new ArrayList<String>();
list.add(clientValue.substring(0, clientValue.length()-2));
list.add(clientValue.substring(clientValue.length()-2));

Upvotes: 1

lkaradashkov
lkaradashkov

Reputation: 8899

string tmp = "56427R1";

ArrayList<String> arrList = new ArrayList()<String>;
arrayList.add(tmp.substring(tmp.length() - 2));
arrayList.add(tmp.substring((tmp.length() - 2), tmp.length()));

Upvotes: 0

Related Questions