如何在Java中按逗号和换行符(\n)拆分字符串?

huangapple go评论90阅读模式
英文:

How to split string by comma and newline (\n) in Java?

问题

String string = "New York,USA,1000\n" +
                "City,World,2000\n";

String[] newline = string.split("\n");
String[] result = new String[1000]; // It seems like you intended to initialize an array, not a string

for (int i = 0; i < newline.length; i++) {
    result = newline[i].split(",");
    // Now you can access the elements of 'result' array for further processing
}
英文:

So I have this string :
"New York,USA,1000\n" +
"City,World,2000\n";

I need to split it first by newline and then by comma, so at the end I get an array of strings that is like this: New York has index 0, USA index 1, 1000 index 2, World index 4 and so on..I tried using
String[] newline = string.split(&quot;\n&quot;) and then declaring a new array of strings called result ( giving it 1000 characters randomly ) and making a for loop like this:

String[] result = new String[1000];
for (String s : newline){
  result=s.split(&quot;,&quot;);
}

But it doesn't work properly. Any help, please?

答案1

得分: 1

不同的操作系统有不同的换行符:

请查阅 https://en.wikipedia.org/wiki/Newline

  • UNIX或Mac:\r

  • Windows:\r\n

     String[] lines = text.split(&quot;\\r?\\n&quot;);
     for (String line : lines) {
         System.out.println(&quot;line  : &quot; + line);
         String[] words = line.split(&quot;,&quot;);
         System.out.println(&quot;words : &quot; + words);
     }
    
英文:

Different operating system has a different new line

Please check https://en.wikipedia.org/wiki/Newline

  • UNIX or Mac \r

  • Windows \r\n

     String[] lines = text.split(&quot;\\r?\\n&quot;);
     for (String line : lines) {
         System.out.println(&quot;line  : &quot; + line);
         String[] words = line.split(&quot;,&quot;);
         System.out.println(&quot;words : &quot; + words);
     }
    

答案2

得分: 1

如果您正在使用Java 8或更高版本请尝试类似以下的代码

    
    String str = "New York,USA,1000\n" + "City,World,2000\n";
    String[] result = Pattern.compile("\n")
                             .splitAsStream(str)
                             .map(s -> s.split(","))
                             .flatMap(Arrays::stream)
                             .toArray(String[]::new);
英文:

If you are using java 8 or higher try try something like:

String str =  &quot;New York,USA,1000\n&quot; + &quot;City,World,2000\n&quot;;
String[] result = Pattern.compile(&quot;\n&quot;)
                         .splitAsStream(str)
                         .map(s -&gt; s.split(&quot;,&quot;))
                         .flatMap(Arrays::stream)
                         .toArray(String[]::new);

答案3

得分: 1

public class Test {
    public static void main(String[] args) {
        String string = "New York,USA,1000\n" + "City,World,2000\n";
        String[] newline = string.split("\n");
        String[] result = new String[1000];
        int index = 0;
        for (String s : newline) {
            for (String t : s.split(",")) {
                result[index++] = t;
            }
        }
        for (int i = 0; i < index; i++) {
            System.out.print(result[i] + " ");
        }
    }
}
/*
output:
New York USA 1000 City World 2000 
 */
英文:
public class Test {
    public static void main(String[] args) {
        String string = &quot;New York,USA,1000\n&quot; + &quot;City,World,2000\n&quot;;
        String[] newline = string.split(&quot;\n&quot;);
        String[] result = new String[1000];
        //first loop
        result = newline[0].split(&quot;,&quot;);
        System.out.println(Arrays.toString(result));
        //second loop
        result = newline[1].split(&quot;,&quot;);
        System.out.println(Arrays.toString(result));
    }
}
/*
output:
[New York, USA, 1000]
[City, World, 2000]
 */

result would be overrided instead of append.

public class Test {
    public static void main(String[] args) {
        String string = &quot;New York,USA,1000\n&quot; + &quot;City,World,2000\n&quot;;
        String[] newline = string.split(&quot;\n&quot;);
        String[] result = new String[1000];
        int index = 0;
        for (String s : newline) {
            for (String t : s.split(&quot;,&quot;)) {
                result[index++] = t;
            }
        }
        for (int i = 0; i &lt; index; i++) {
            System.out.print(result[i] + &quot; &quot;);
        }
    }
}
/*
output:
New York USA 1000 City World 2000 
 */

答案4

得分: 0

如果我理解正确

    import re
    
    stringobject = "New York,USA,1000\n" + "City,World,2000\n"
    
    emptylist = []
    for str_obj in stringobject.splitlines():
        o = str_obj.split(sep=",")
        emptylist.append(o)

    print(emptylist)

    [['New York', 'USA', '1000'], ['City', 'World', '2000']]

可以访问的嵌套列表

    print(emptylist[0][0])
    'New York'
英文:

If I get you correctly:

import re

stringobject = &quot;New York,USA,1000\n&quot; + &quot;City,World,2000\n&quot;

emptylist = []
for str_obj in stringobject.splitlines():
    o = str_obj.split(sep=&quot;,&quot;)
    emptylist.append(o)

print(emptylist)

[[&#39;New York&#39;, &#39;USA&#39;, &#39;1000&#39;], [&#39;City&#39;, &#39;World&#39;, &#39;2000&#39;]]

Which is a list of list and can be accessed:

print(emptylist[0][0])
&#39;New York&#39;

huangapple
  • 本文由 发表于 2020年4月4日 21:55:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/61029164.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定