我想将一个字符串拆分成一个 ArrayList。 示例:
String = "你想得到对你问题的回复吗" 数量为 3 的结果:Wou -> arraylist,ld -> arraylist,you -> arraylist,...
数量是一个预定义的变量。
到目前为止:
public static void analyze(File file) {
ArrayList<String> splittedText = new ArrayList<String>();
StringBuffer buf = new StringBuffer();
if (file.exists()) {
try {
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis,
Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(isr);
String line = "";
while ((line = reader.readLine()) != null) {
buf.append(line + "\n");
splittedText.add(line + "\n");
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
String wholeString = buf.toString();
wholeString.substring(0, 2); //here comes the string from an txt file
}
最佳答案
执行此操作的“正常”方法是您所期望的:
List<String> splits = new ArrayList<String>();
for (int i = 0; i < string.length(); i += splitLen) {
splits.add(string.substring(i, Math.min(i + splitLen, string.length()));
}
我将使用 Guava 抛出一个单行解决方案, 尽管。 (披露:我为 Guava 做出了贡献。)
return Lists.newArrayList(Splitter.fixedLength(splitLen).split(string));
仅供引用,您可能应该使用 StringBuilder
而不是 StringBuffer
,因为它看起来不像您需要线程安全。
关于java - 根据选定的字符数拆分 ArrayList 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10235242/