我有一个包含许多行的文本文件,每行包含许多用分隔符分隔的单词,例如" hello,world,I,am,here"。
我想在位置和分隔符之间提取一些单词,例如: 这个位置是7,所以字符串是" world"如果位置为1,则字符串将为" hello"
答案 0 :(得分:2)
我建议使用split()
方法。用逗号分隔单词,你可以这样做:
String[] words = "hello,world,I,am,here".split(",");
然后你可以通过索引到数组来获取位置:
words[3] // would yield "am"
请注意,split()
的参数是正则表达式,因此如果您不熟悉它们see the docs here(或谷歌的教程)。
答案 1 :(得分:1)
在利用可用于所有Strings对象的方法split()
时,只需实现以下代码:
String line = "hello,world,I,am,here";
String[] words = line.split(",");
答案 2 :(得分:0)
public static String wordAtPosition(String line, int position) {
String[] words = line.split(",");
int index = 0;
for (String word : words) {
index += word.length();
if (position < index) {
return word;
}
}
return null;
}
实施例
String line = "hello,world,I,am,here";
String word = wordAtPosition(line, 7);
System.out.println(word); // prints "world"
答案 3 :(得分:0)
首先获取子字符串,然后拆分并从Array获取第一个元素。
public class Test {
public static void main(String[] args) throws ParseException {
Test test = new Test();
String t = test.getStringFromLocation("hello,world,I,am,here", 1, ",");
System.out.println(t);
t = test.getStringFromLocation("hello,world,I,am,here", 7, ",");
System.out.println(t);
t = test.getStringFromLocation("hello,world,I,am,here", 6, ",");
System.out.println(t);
}
public String getStringFromLocation(final String input, int position,
String demlimter) {
if (position == 0) {
return null;
}
int absoulutionPosition = position - 1;
String[] value = input.substring(absoulutionPosition).split(demlimter);
return value.length > 0 ? value[0] : null;
}
}
答案 4 :(得分:0)
不是最易读的解决方案,但涵盖了极端情况。拆分解决方案很好,但不反映原始字符串中的位置,因为它从计数中跳过','
String line = "hello,world,I,am,here";
int position = new Random().nextInt(line.length());
int startOfWord = -1;
int currentComa = line.indexOf(",", 0);
while (currentComa >= 0 && currentComa < position) {
startOfWord = currentComa;
currentComa = line.indexOf(",", currentComa + 1);
}
int endOfWord = line.indexOf(",", position);
if(endOfWord < 0) {
endOfWord = line.length();
}
String word = line.substring(startOfWord + 1, endOfWord);
System.out.println("position " + position + ", word " + word);