DTRobertson94
DTRobertson94

Reputation: 201

Splitting Elements in an Array

I have an array consisting of a color shading (lightgreen, red, blue, etc.) as well as having a number in regards to the colors "strength" (1000, 1200, 400, etc.)

The lines are read in through a .txt file as follows

light green 1200

red 1000

blue 400

I was wondering if there is a way to split the two elements into distinct arrays (one for String and one for int) so that I can sort the array by the strengths into ascending order.

Upvotes: 0

Views: 202

Answers (3)

Deepak Sharma
Deepak Sharma

Reputation: 4170

if you want to get the color string value and different array and their numeric value in different array(int), them use the split to splt the string value u read from txt file then add the add in created arrays

Lets consider if you have arr as array has values from txt file, now we want to get the string value in color array and their numeric value in val array, i think below code will help u out.

String []arr = {"col 1 200","col 2 10","col 3 500"};

String []color = new String[arr.length];
int []val = new int[arr.length];

String []temp;

for (int i = 0; i < arr.length; i++) {
    temp = arr[i].trim().split(" ");

    for (int j = 0; j < temp.length -1; j++) {
        if(color[i]==null)
            color[i]="";
        color[i] += temp[j]+" ";
    }

    color[i] =color[i].trim();      
    val[i] = Integer.parseInt(temp[temp.length-1]);
}

it will not add col 1, col 2 and col 3 in color array and value 200, 10, 500 in val array(int)

--OUTPUT--

if you print

color -- ["col 1", "col 2", "col 3"]
val -- [200, 10, 500]

Upvotes: 0

Masudul
Masudul

Reputation: 21961

You can solve your problem in following steps.

  1. Read the txt file line by line.
  2. Split the every line into color and strength.
  3. Store the strength as key and color as value into TreeMap.

Note: TreeMap will sort your data in ascending order according to key. If you have duplicate stength but unique color than Store the color as key and strength as value into HashMap and sort the HashMap according to value.

Upvotes: 1

aelor
aelor

Reputation: 11116

you can use awk :

cat file | awk '{print $1}' > file1

and

cat file | awk '{print $2}' > file2

so file 1 will have the list of colors and file 2 will have the list of strengths.

Now you can push the int values to do whatever you like.

Alternative : You can follow the regex route:

str = "Red 1000";
String[] splited = str.split("\\s+(?=\\d)");

this will only split it before the number i.e. "strength":

demo here : http://regex101.com/r/cF6qD6

Upvotes: 1

Related Questions