如何通过换行拆分字符串? [重复]

时间:2021-08-17 07:54:27

This question already has an answer here:

这个问题在这里已有答案:

I'm a noob to android development and I am trying to split a string multiple times by its multiple line breaks. the string I'm trying to split is pulled from a database query and is constructed like this:

我是Android开发的菜鸟,我试图通过多个换行符多次拆分字符串。我正在尝试拆分的字符串是从数据库查询中提取的,并且构造如下:

public String getCoin() {
    // TODO Auto-generated method stub
    String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_QUANTITY, KEY_OUNCES, KEY_VALUE };
    Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
    String result = "";

    int iRow = c.getColumnIndex(KEY_ROWID);
    int iName = c.getColumnIndex(KEY_NAME);
    int iQuantity = c.getColumnIndex(KEY_QUANTITY);
    int iOunces = c.getColumnIndex(KEY_OUNCES);
    int iValue = c.getColumnIndex(KEY_VALUE);

    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
        result = result + /*c.getString(iRow) + " " +*/ c.getString(iName).substring(0, Math.min(18, c.getString(iName).length())) + "\n";
    }
    c.close();
    return result;

result.getCoin reads as this:

result.getCoin读成:

alphabravocharlie

I want to split the string at the line break and place each substring into a String Array. This is my current code:

我想在换行符处拆分字符串并将每个子字符串放入一个字符串数组中。这是我目前的代码:

String[] separated = result.split("\n");
      for (int i = 0; i < separated.length; i++) {
           chartnames.add("$." + separated[i] + " some text" ); 
           }

This gives me an output of:

这给了我一个输出:

"$.alpha
bravo
charlie some text"

instead of my desired output of:

而不是我想要的输出:

"$.alpha some text, $.bravo some text, $.charlie some text"

Any help is greatly appreciated

任何帮助是极大的赞赏

6 个解决方案

#1


43  

you can split a string by line break by using the following statement :

您可以使用以下语句按换行符拆分字符串:

   String textStr[] = yourString.split("\\r\\n|\\n|\\r");

#2


19  

It's a little overkill, but you can use the standard I/O classes:

这有点矫枉过正,但你可以使用标准的I / O类:

BufferedReader rdr = new BufferedReader(new StringReader(result));
List<String> lines = new ArrayList<String>();
for (String line = rdr.readLine(); line != null; line = rdr.readLine()) {
    lines.add(line);
}
rdr.close(); // good form to close streams, but unnecessary for StringReader

// lines now contains all the strings between line breaks of any type

The advantage of this is that BufferedReader.readLine() has all the logic worked out for detecting all sorts of line terminators.

这样做的好处是BufferedReader.readLine()具有用于检测各种线路终结器的所有逻辑。

As of Java 8, BufferedReader has a lines() method, so there's an easier way (thanks, @jaco0646):

从Java 8开始,BufferedReader有一个lines()方法,所以有一种更简单的方法(谢谢,@ jaco0646):

List<String> lines = new BufferedReader(new StringReader(result))
                         .lines()
                         .collect(Collectors.toList();

or, if an array is needed instead:

或者,如果需要一个数组:

String[] lines = new BufferedReader(new StringReader(result))
                     .lines()
                     .toArray(String[]::new);

#3


4  

Using the Apache commons helper class StringUtils.

使用Apache commons帮助程序类StringUtils。

The platform independent way:

平*立方式:

String[] lines = StringUtils.split(string, "\r\n");

String [] lines = StringUtils.split(string,“\ r \ n”);

The platform dependent way. Maybe some CPU cycles faster. But I wouldn't expect it to matter.

平台依赖的方式。也许一些CPU周期更快。但我不认为这很重要。

String[] lines = StringUtils.split(string, System.lineSeparator());

String [] lines = StringUtils.split(string,System.lineSeparator());

#4


2  

If possible I would suggest using the Guava Splitter and Joiner classes in preference to String.split. But even then, it's important to make sure that you're properly escaping your regular expressions when declaring them. I'm not certain "\n" won't be properly interpreted by the regex compiler in Java, but I'm not sure it will be either.

如果可能的话,我会建议使用Guava Splitter和Joiner类而不是String.split。但即便如此,确保在声明它们时正确地转义正则表达式也很重要。我不确定“\ n”是否会被Java中的正则表达式编译器正确解释,但我不确定它是否也是如此。

Covering all possible line endings is tricky, since multiple consecutive EOL markers can mess up your matching. I would suggest

覆盖所有可能的行结尾是很棘手的,因为多个连续的EOL标记会弄乱您的匹配。我会建议

String [] separated = result.replaceAll("\\r", "").split("\\n");

#5


1  

Matcher m = Pattern.compile("(^.+$)+", Pattern.MULTILINE).matcher(fieldContents);

while (m.find()) {
    System.out.println("whole group " + m.group())
}

#6


0  

I propose the following snippet, which is compatiple with PC and Mac endline styles both.

我建议使用以下代码片段,它兼容PC和Mac端线样式。

String [] separated = result.replaceAll("\\r", "\\n")
   .replaceAll("\\n{2,}", "\\n")
   .split("\\n");

#1


43  

you can split a string by line break by using the following statement :

您可以使用以下语句按换行符拆分字符串:

   String textStr[] = yourString.split("\\r\\n|\\n|\\r");

#2


19  

It's a little overkill, but you can use the standard I/O classes:

这有点矫枉过正,但你可以使用标准的I / O类:

BufferedReader rdr = new BufferedReader(new StringReader(result));
List<String> lines = new ArrayList<String>();
for (String line = rdr.readLine(); line != null; line = rdr.readLine()) {
    lines.add(line);
}
rdr.close(); // good form to close streams, but unnecessary for StringReader

// lines now contains all the strings between line breaks of any type

The advantage of this is that BufferedReader.readLine() has all the logic worked out for detecting all sorts of line terminators.

这样做的好处是BufferedReader.readLine()具有用于检测各种线路终结器的所有逻辑。

As of Java 8, BufferedReader has a lines() method, so there's an easier way (thanks, @jaco0646):

从Java 8开始,BufferedReader有一个lines()方法,所以有一种更简单的方法(谢谢,@ jaco0646):

List<String> lines = new BufferedReader(new StringReader(result))
                         .lines()
                         .collect(Collectors.toList();

or, if an array is needed instead:

或者,如果需要一个数组:

String[] lines = new BufferedReader(new StringReader(result))
                     .lines()
                     .toArray(String[]::new);

#3


4  

Using the Apache commons helper class StringUtils.

使用Apache commons帮助程序类StringUtils。

The platform independent way:

平*立方式:

String[] lines = StringUtils.split(string, "\r\n");

String [] lines = StringUtils.split(string,“\ r \ n”);

The platform dependent way. Maybe some CPU cycles faster. But I wouldn't expect it to matter.

平台依赖的方式。也许一些CPU周期更快。但我不认为这很重要。

String[] lines = StringUtils.split(string, System.lineSeparator());

String [] lines = StringUtils.split(string,System.lineSeparator());

#4


2  

If possible I would suggest using the Guava Splitter and Joiner classes in preference to String.split. But even then, it's important to make sure that you're properly escaping your regular expressions when declaring them. I'm not certain "\n" won't be properly interpreted by the regex compiler in Java, but I'm not sure it will be either.

如果可能的话,我会建议使用Guava Splitter和Joiner类而不是String.split。但即便如此,确保在声明它们时正确地转义正则表达式也很重要。我不确定“\ n”是否会被Java中的正则表达式编译器正确解释,但我不确定它是否也是如此。

Covering all possible line endings is tricky, since multiple consecutive EOL markers can mess up your matching. I would suggest

覆盖所有可能的行结尾是很棘手的,因为多个连续的EOL标记会弄乱您的匹配。我会建议

String [] separated = result.replaceAll("\\r", "").split("\\n");

#5


1  

Matcher m = Pattern.compile("(^.+$)+", Pattern.MULTILINE).matcher(fieldContents);

while (m.find()) {
    System.out.println("whole group " + m.group())
}

#6


0  

I propose the following snippet, which is compatiple with PC and Mac endline styles both.

我建议使用以下代码片段,它兼容PC和Mac端线样式。

String [] separated = result.replaceAll("\\r", "\\n")
   .replaceAll("\\n{2,}", "\\n")
   .split("\\n");