简体   繁体   中英

Java split a string into an array by newline

Edit: I have modified the question for simplicity.

I have this method to split a long string into an array of strings and it shall return a double string, so that I can write it on a .csv file later:

public class Test {
    public static void main(String[] args) throws IOException {
        String test = "Michael Porter Jr. 2018-19 Panini Prizm Silver Prizm PSA 10 Gem Mint! Hot! ?? \n 2018 Prizm Silver MICHAEL PORTER JR. RC PSA 10 Gem Mint";
        System.out.println(test);
        String[] test_split = test.split("\\r?\\n");
        for (String t : test_split) {
            System.out.println(test_split.toString());
        }

    }

}

My code returns this:

Michael Porter Jr. 2018-19 Panini Prizm Silver Prizm PSA 10 Gem Mint! Hot! ?? 
 2018 Prizm Silver MICHAEL PORTER JR. RC PSA 10 Gem Mint
[Ljava.lang.String;@4a574795
[Ljava.lang.String;@4a574795

I actually expected to have an arrays with the 2 names (split by the newline character), but I got something weird. How may I fix this please?

You seem to be printing out an Array of Strings not a String, judging by the output you posted, without really seeing in which way you actually call eg println. If this is really the case you could also use:

Arrays.toString(yourArray);

It might be better if you reversed the arrays. Make them a 2xN instead of an Nx2 Here is a segment of your method.

         String[][] nameAndPrice = new String[2][listingName_extract.length];

         for (int i = 0; i < listingName_extract.length; i++) {
              nameAndPrice[0][i] = String.valueOf(listingName_extract[i]);
              nameAndPrice[1][i] = String.valueOf(listingPrice_extract[i]);
          }
         return nameAndPrice;

And you should probably be using Arrays.toString() to print out the array.

System.out.println(Arrays.toString(nameAndPrice[0]);
System.out.println(Arrays.toString(nameAndPrice[1]);

Then if you want to print them side by side.

 for (int i = 0; i < listingName_extract.length; i++) {
     System.out.println(nameAndPrice[0][i] + " " + nameAndPrice[1][i]);
 }

As users TheThingAboveMe and Andreas suggested, I should be looking at t (the strings) and not the test_split (the array itself).

I have also edited my code per user WJS's suggestion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM