简体   繁体   English

Java按行拆分字符串\\ n不起作用

[英]java splitting a string by line \n not working

So I have a string which is from a text file, essentially the text file is just 5 lines which read: 所以我有一个来自文本文件的字符串,从本质上讲,文本文件只有5行,内容为:

x=1
y=15
z=128
topx=100
leftx=150
label= this is a test

I am able to get the split to work once which separates via the '=' sign, but when I try to split the string again by \\n nothing works, I have tried using "\\r?\\n", line.Separator etc. but the string value always stays the same, basically the 5 lines without the characters before the = sign. 我能够使拆分工作一次,该拆分通过'='符号分隔,但是当我尝试再次通过\\ n拆分字符串时,没有任何效果,我尝试使用“ \\ r?\\ n”,line.Separator等。,但字符串值始终保持不变,基本上是5行,其中=号前没有字符。 How would I pull out the individual lines to assign variables to? 我如何拔出单独的行来分配变量?

Here is the code I have, basically the println is to try and see if I can get the first value '1' to list separate from the rest of the lines. 这是我的代码,基本上println是尝试查看是否可以获取第一个值“ 1”以与其余各行分开列出。

    public static void main(String[] a) {
 15   draw d = new draw();
 16   Read r = new Read();
 17   String m = r.doRead("variables.txt");
 18 
 19   String[] ss = new String[5];  
 20   ss = m.split("\n");
 21 
 22   String[] kv= new String[5];
 23   for (int i=0; i<ss.length; i++) {
 24           kv = ss[i].split("=");
 25           String eol = System.getProperty("line.seperator"); 
 26           String test = kv[1];
 27           String[] split = new String[5];
 28           split = test.split("\n");
 29           
 30           
 31 
 32            
 33           String first = split[0];  
 34           //String second = split[1];       
 35           //String third = split[2];
 36           //String fourth = split[3];
 37           //String fifth = split[4];      
 38           System.out.println(first);
 39           }

When every line looks like 当每一行看起来像

x=1 y=15 z=128 topx=100 leftx=150 label= this is a test

you should first split at a whitespace to get 5 parts ( x=1 , y=15 , ...) and then at = to get the "key" and "value" part of each part. 您应该首先在空白处拆分以获取5个部分( x=1y=15 ,...),然后在=处拆分以获取每个部分的“键”和“值”部分。

check this out: 看一下这个:

String s = "x=1\ny=15\nz=128\ntopx=100\nleftx=150\nlabel= this is a test";
String[] ss = s.split("\n");
System.err.println( Arrays.asList(ss[0].split("=")) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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