如何从Java中的字符串中提取单词 [英] How to extract words from a string in Java
问题描述
我已经导入了一个文件,并将其转换为一个名为readFile的字符串.该文件包含两行:
I've imported a file and turned it into a String called readFile. The file contains two lines:
qwertyuiop00%
qwertyuiop
我已经使用以下命令从字符串中提取了"00": 字符串号= readFile.substring(11,13);
I have already extracted the "00" from the string using: String number = readFile.substring(11, 13);
我现在要提取"qwertyuiop"中的"ert"和"uio" 当我尝试使用与第一种相同的方法时,就像这样:
I now want to extract the "ert" and the "uio" in "qwertyuiop" When I try to use the same method as the first, like so:
String e = readFile.substring(16, 19);
String u = readFile.substring(20, 23);
并尝试使用:
System.out.println(e + "and" + u);
它表示字符串索引超出范围.
It says string index out of range.
我该如何处理? 是因为我要从字符串中提取的下两个单词在第二行吗? 如果是这样,我如何仅提取第二行? 我想保持基本状态,谢谢.
How do I go about this? Is it because the next two words I want to extract from the string are on the second line? If so, how do I extract only the second line? I want to keep it basic, thanks.
更新: 原来只读取文件的第一行,有人知道如何制作它以便读取两行吗?
UPDATE: it turns out only the first line of the file is being read, does anyone know how to make it so it reads both lines?
推荐答案
您可以尝试一下:-
Scanner sc=new Scanner(new FileReader(new File(The file path for readFile.txt)));
String st="";
while(sc.hasNext()){
st=sc.next();
}
System.out.println(st.substring(2,5)+" "+"and"+" "+st.substring(6,9));
检查它是否有效.
这篇关于如何从Java中的字符串中提取单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!