m1ddleware
m1ddleware

Reputation: 78

Converting a string[] into a string then split into an array

I need help creating a loop which splits strings. So far I have the code below.

    System.out.println("*FILE HAS BEEN LOCATED*");
    System.out.println("*File contains: \n");
    List<String> lines = new ArrayList<String>();
    while (scan.hasNextLine()) 
    {
      lines.add(scan.nextLine());
    }

    String[] arr = lines.toArray(new String[0]);

    String str_array = Arrays.toString(arr);

    String[] arraysplit;
    arraysplit = str_array.split(":");

    for (int i=0; i<arraysplit.length; i++)
    {
        arraysplit[i] = arr[i].trim();
        System.out.println(arr[i]);
    }

an example of one of the strings would be

        Firstname : Lastname : age 

I want it to split the string into another array that looks like:

        Firstname
        Lastname
        age

I still encounter an error when running the code, it seems as though when I convert the array to a string, it puts commas in the string and therefore it causes problems as I'm trying to split the string on : not ,

image: IMAGE, I've circled where the commas are within the converted array string

Upvotes: 0

Views: 66

Answers (2)

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

Issue : you are using the old array arr to display values and arraysplit will have resultant values of split method so you need to apply trim() on arraysplit's elements and assign back the elements to same indexes

String[] arraysplit;
arraysplit = str_array.split(":");

for (int i=0; i<arraysplit.length; i++)
{
    arraysplit[i] = arraysplit[i].trim();
    //              ^^^^^^^^^^^^ has values with spaces
    System.out.println(arr[i]);
}

System.out.println(arraysplit[i]);

To simplify solution without (list to array and array to string complication)

1.) Create array of length as sizeOfList * 3

2.) split the list element using \\s*:\\s*

3.) Use array copy with jas index of resultant array to keep the track of the array index

    String result[] = new String [lines.size()*3];
    int j=0;
    for (int i=0; i<lines.size(); i++)
    {
        System.arraycopy(lines.get(0).split("\\s*:\\s*"), 0, result, j, 3);
        j+=3;
    }
    System.out.println(Arrays.toString(result));

You can use regex str_array.split("\\s*:\\s*"); where

\\s*:\\s* : \\s* mean zero or more spaces then : character then zero or more spaces

arraysplit = str_array.split("\\s*:\\s*");
// just use values of arraysplit

Upvotes: 5

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59960

Split using this regex \s*:\s*

String[] arraysplit = str_array.split("\\s*:\\s*");

details :

  • \s* zero or more spaces
  • followed by lateral character :
  • followed by \s* zero or more spaces

regex demo

Upvotes: 2

Related Questions