有一个长字符串 - “sourceMeaning”,它包含从SQLiteDatabase中检索的一些句子。我用过“&”分开如下句子:
SentenceA&SentenceB&SentenceC .....
检索到长字符串后,字符串将分为:
SentenceA
SentenceB
SentenceC
....
我使用String数组(Meanings)来存储分割的句子并应用以下代码来完成任务,但是在执行时抛出StringIndexOutOfBoundsException ...
String sourceMeaning=c.getString(1);
Log.w("SourceMeaning",sourceMeaning);
String[] Meanings=new String[]{};
int j=0;
for (int i=0;i<=sourceMeaning.length();i++){
if (sourceMeaning.charAt(i)!='&'){
Meanings[j]=Meanings[j]+sourceMeaning.charAt(i);
Log.w("Translated",Meanings[j]);
} else {
j+=1;
}
}
如何无错误地划分句子?
答案 0 :(得分:2)
您可以使用split()然后遍历生成的数组:
String[] sentences = sourceMeaning.split("&");
for (String sentence: sentences) {
//iterate through each one of the sentences, i.e:
//SentenceA, SentenceB, ....
}
答案 1 :(得分:0)
答案 2 :(得分:0)
你应该以这种方式分割初始字符串
String sourceMeaning=c.getString(1);
Log.w("SourceMeaning",sourceMeaning);
String[] meanings = sourceMeaning.split("&");
你将拥有该数组中的所有内容
答案 3 :(得分:0)
您可以使用str.split()
方法将字符串转换为数组:
String[] Meanings = sourceMeaning.split("&");