如何按“换行符”拆分字符串?

6
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str
while ((str =in.readLine()) != null)
{
     items = str.split("\n");
}
in.close();

字符串(str)包含来自文本文件的数据,例如:

一月

二月

三月

等等。

每个单词都在新行上。我想读取该字符串并将每个单词分隔到一个新行中,并存储到一个字符串对象数组中(这将是名为“items”的变量)。

7个回答

12

事实上,BufferedReader.readLine 已经 根据换行符拆分了输入。

所以,你当前的代码:

items=str.split("\n");

你只需要将str添加到数组中即可。

例如,使用infile文件:

January
February
March
April
May
June

下面的程序输出6(创建的数组列表的大小):

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
class Test {
    public static void main (String[] args) {
        try {
            ArrayList<String> itms = new ArrayList<String> ();
            BufferedReader br = new BufferedReader (new FileReader ("infile"));
            String str;
            while ((str = br.readLine()) != null)
                itms.add(str);
            br.close();
            System.out.println (itms.size());
        } catch (Exception e) {
            System.out.println ("Exception: " + e);
        }
    }
}

2
< p > readLine 方法已经逐行读取。在这个字符串中将没有 \n 字符。

可以尝试使用以下代码:

ArrayList<String> itemList = new ArrayList<String>();
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
    itemList.add(str);
}
in.close();

1

这是我的代码,它对我有效。

private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        String response = "";
        for (String url : urls) {
            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            ArrayList<String> itemList = new ArrayList<String>();
            try {
                HttpResponse execute = client.execute(httpGet);
                InputStream content = execute.getEntity().getContent();

                BufferedReader buffer = new BufferedReader(
                        new InputStreamReader(content, "iso-8859-1"));
                StringBuilder sb = new StringBuilder();

                String s = null;

                while ((s = buffer.readLine()) != null) {

                    itemList.add(s);


                }

                response = itemList.get(0);
                content.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return response;
    }

    @Override
    protected void onPostExecute(String result) {
        textView.setText(Html.fromHtml(result));
    }
}

public void readWebpage(View view) {
    DownloadWebPageTask task = new DownloadWebPageTask();
    task.execute(new String[] { "http://www.yourURL.com" });

}

readWebpage函数是我在按钮xml中创建的onclick函数,如下所示。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>

<Button android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/readWebpage" android:onClick="readWebpage" android:text="Load Webpage"></Button>
<TextView android:id="@+id/TextView01" android:layout_width="match_parent" android:layout_height="match_parent" android:text="Example Text"></TextView>

在我的代码中,我尝试获取第一行,所以我使用itemList.get(0)。如果你想获取另一行,只需更改索引,比如itemList.get(1)或itemList.get(n)。请注意,保留html标签。

0

使用 ArrayList 来完成这个任务。

ArrayList<String> items= new ArrayList<String>();

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str =in.readLine()) != null)
{
    items.add(str.split("\n"));
}
in.close();

=====>检查中

 for(int i=0;i<items.size;i++)
 {
    System.out.println("item name "+items.get(i));
 }

0

如何通过换行符拆分字符串

我来到这个问题只是想要拆分一个字符串,而不是一个文件。所以我将在这里为未来的访问者回答。

假设

String myString = "one/ntwo/nthree";

你可以使用以下代码将其转换为数组

String myArray[] = myString.split("\n");    // {"one", "two", "three"};

如果需要,可以用以下代码将其转换为 List

List myList = new ArrayList();
Collections.addAll(myList, myArray);

0
在Android/Java中,这非常简单。按照以下步骤:
假设
String txt="I am Rahul Kushwaha.I am an Android Developer";

现在,要将其按行拆分,请使用split()方法。例如:
String txt_split=txt.split("\n");
System.out.println(txt_split);

输出:

I
am
Rahul
Kushwaha
.
I
am
an
Android
Developer

现在,要获取分割字符串的长度,请使用length()方法。
int txt_length=txt_split.length();
System.out.println("text length=",txt_length);

输出:-

text length=10

按行访问特定数据。可以这样做:-
String[] text_data=txt.split("\n");

System.out.println("Name :",text_data[2]);
System.out.println("Title :",text_data[3]);
System.out.println("Job :",text_data[8]);

输出:-

Name :Rahul
Title :Kushwaha
Job :Android

希望这能对你有所帮助。谢谢...


0
如果您想保留所有的空行,那么可以使用以下代码:
String lines[] = givenString.split("\\r?\\n", -1);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接