[英]trying to read from a file and split it into words and store those words in an arrayList
in my code when i want to print out the list , there is return of line and i don't know how to get rid of it, for example if my file contain those lines: 在我的代码中,当我想打印出列表时,有行的返回并且我不知道如何清除它,例如,如果我的文件包含这些行:
i can't think of anything to write 我想不起要写什么
blah blah blah 等等等等等等
when i print out my list i got this: 当我打印出我的清单时,我得到了:
{i, can't, think, of, anything, to, write {i,想不出要写什么
blah,blah , blah} 等等等等等等}
this is my code: 这是我的代码:
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>() ;
try(BufferedReader br = new BufferedReader(new FileReader("test.txt"));){
int i = 0;
String str = " ";
while((i = br.read()) != -1){
str += (char) i;
if( (char) i == ' '){
list.add(str.toString());
str = " " ;
}
}
list.add(str.toString());
}catch (Exception e){
System.out.println("there is an exception ");
}
printArrayList(list);
}
public static void printArrayList(ArrayList<String> list){
System.out.print("{");
for(int i = 0; i<list.size(); i++){
if (i > 0)
System.out.print("," + list.get(i));
else
System.out.print(list.get(i));
}
System.out.print("}");
}
Are you opposed to importing a library? 您反对导入库吗? Apache StringUtils has a method that splits on whitespace, returning everything else in tokens. Apache StringUtils有一个在空格上分割的方法,以令牌形式返回其他所有内容。
https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#split%28java.lang.String%29 https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#split%28java.lang.String%29
This is happening because you are only splitting the sentence when you find a space if( (char) i == ' ')
. 之所以发生这种情况,是因为您仅在找到空格if( (char) i == ' ')
时才拆分句子。 If you want to split it on new lines also, use 如果您还想将其拆分为新行,请使用
if ( (char) i == ' ' || (char) i == '\\n')
Note: \\n
is not the line separating character in all the platforms. 注意: \\n
并非在所有平台中都使用行分隔符。 AFAIK, it can be anyone of \\n
or \\r
or \\r\\n
.. AFAIK,它可以是\\n
或\\r
或\\r\\n
。中的任何一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.