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?
It works on any system.
String[] array = str.split(System.getProperty("line.separator"));
You can use split().
split()
String s[] = input.split("\n"); // "\n" if it is only a new-line. "\r\n" if you use windows OS.
Java 8 :
Files.readAllLines(Path)
a List<String>. , .
List<String>
Files.lines(Path)
Stream<String>. .
Stream<String>
Another approach. Divide into everything that is not between [a-zA-Z]. It works on different platforms:
[a-zA-Z]
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]
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(); }
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("[ ]+");
Source: https://habr.com/ru/post/1628302/More articles:nested dictionary size and list - pythonhttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1628298/adding-selected-data-frames-together-from-a-list-of-data-frames&usg=ALkJrhghPbYBShJPQTirVqDlhwVR93VnPAComparing Javascript Date looks weird - javascripthttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1628300/fliped-cursor-icon-on-desktop-recording-using-directshow&usg=ALkJrhg9XJTAS6BX4SQno9U5-Cx-6MDZvgJackson Json deserializing an object to a list - javaImage appears stretched after loading Placeholder image via Glide? - androidAngular2 - Multiselect & Checkboxes - only the last selected values are displayed - angularUltra Numeric Editor устанавливает значение по умолчанию до 2 знаков после запятой - c#Using a generic parameter for overloaded methods - genericsPHP does not use updated OpenSSL for Mac OS X - phpAll Articles