我有一个我尝试拆分的字符串。以下代码可以使用
lsSagor = "some text\n Some more text\n More text~Text again\n Text\n text~Some text ..."
final String[] laList = lsSagor.split("~");
String[] laSaga = laList[0].split("\n");
给出:
laSaga[0] => some text
laSaga[1] => some more text
laSaga[2] => More text
但是如果我下载文本文件,则无法拆分并给出:
laSaga[0] => "some text\n Some more text\n More text"
所以看起来第一次拆分工作,但不是第二次。
以下是我用来下载文件的代码
String lsSagor = getFileFromUrl(BASEURL+"/sagor.txt");
public static String getFileFromUrl(String url)
{
InputStream content = null;
try
{
HttpGet httpGet = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
// Execute HTTP Get Request
HttpResponse response = httpclient.execute(httpGet);
content = response.getEntity().getContent();
}
catch (Exception e)
{
//handle the exception !
}
BufferedReader rd = new BufferedReader(new InputStreamReader(content), 4096);
String line;
StringBuilder sb = new StringBuilder();
try {
while ((line = rd.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
rd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
答案 0 :(得分:1)
我认为您不会发现您的字符串包含要拆分的任何换行符,您需要这样做
while ((line = rd.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
要做到这一点,我确信有一种更简单的方法可以直接阅读新行,而且一开始就是这样。
答案 1 :(得分:0)
您好我认为问题出在String.split()函数中
老方法但工作:)
public static String[] splitString(String str, char separator)
{
String[] retVal = null;
int length = str.length();
int size = 1;
int jIndx = 0;
int expressionLength = 0;
while ((jIndx = str.indexOf(separator, jIndx + 1)) != -1)
{
size++;
}
retVal = new String[size];
jIndx = 0;
char[] charArray = str.toCharArray() ;
for (int index = 0; index < length; index++)
{
if (charArray[index] == separator)
{
retVal[jIndx] = str.substring(index - expressionLength, index);
jIndx++;
expressionLength = 0;
}
else
expressionLength++;
if (index + 1 == length)
{
retVal[jIndx] = str.substring(index + 1 - expressionLength, index + 1);
}
}
return retVal;
}
答案 2 :(得分:0)
这是(不那么漂亮)解决方案
lsSagor = "some text# Some more text# More text~Text again\n Text# text~Some text ..."
String lsSagor = getFileFromUrl(BASEURL+"/sagor.txt");
final String[] laList = lsSagor.split("~");
giAntalSagor = laList.length;
String[] laSaga = laList[0].split("#");
final String[] guiLaList = new String[giAntalSagor];
for (int i = 0; i < giAntalSagor; i++)
{
guiLaList[i] = laList[i].replaceAll("#", "\n");
}
guiLaList用于布局“\ n”,另一个列表laList用于获取我想要的信息。