Convert string words to an array of strings

Imagine I have the following line:

hoi
hoe 
gaat 
het

I get this line from a file.

how can i do this in a sting array like this:

String[] hallo = {
        "hoi","hoe","gaat","het"        
        };

What would be the easiest way to achieve this?

+4
source share
6 answers

It works on any system.

String[] array = str.split(System.getProperty("line.separator"));
+6
source

You can use split().

String s[] = input.split("\n"); // "\n" if it is only a new-line. "\r\n" if you use windows OS.
+6
source

Java 8 :

Files.readAllLines(Path)

a List<String>. , .

Files.lines(Path)

Stream<String>. .

+5

Another approach. Divide into everything that is not between [a-zA-Z]. It works on different platforms:

public static void main(String[] args) throws IOException, InterruptedException {
    String s = "asda\r\nasdsa";
    System.out.println(Arrays.toString(s.split("[^a-zA-Z]+")));
}

O / P:

[asda, asdsa]
+3
source
    try {
        File file = new File("file.txt");
        Path path = file.toPath();
        List<String> strings = Files.readAllLines(path); // this is available on **java 8**
     // List<String> strings = FileUtils.readLines(file); // this can be used with **commons-io-2.4 library** 
        for (String s : strings) {
            System.out.println(s);
        }
        String[] string_array = new String[strings.size()];
        for (int i = 0; i < strings.size(); i++) {
            string_array[i] = strings.get(i);
        }
        System.out.println(Arrays.deepToString(string_array));

    } catch (Exception e) {
        e.printStackTrace();
    }
0
source

If the input is on one whole line, you can do this to split the string into an array of strings:

String[] hallo = input.split("[ ]+");
0
source

Source: https://habr.com/ru/post/1628302/


All Articles