我有一个由存储在 ArrayList 中的空格分隔的标记组成的字符串列表。我需要扫描字符串 1 中的标记是否存在于字符串 2 中。我设法使用 Scanner 扫描标记。然而,扫描仪并没有做我想要的事情。
我需要关于以下方面的建议/意见
1. [已编辑] 示例:字符串 1 中有一个 NN 标记,但字符串中有两个 NN 标记
2. 因此,扫描器应该扫描字符串 2 中的 NN token 。使用我提供的代码,扫描器将搜索所有 NN token ,包括第二个 NN token 。它应该在第一个 NN token 处停止,而不是继续扫描所有 NN token 。 {海莉关于休息的建议确实停止了扫描仪}
2. [编辑] 现在,另一个问题是 - 如果字符串 1 有两个 NN 标记,则扫描器应该足够智能,可以跳过先前扫描中找到的所有标记。扫描器应该能够将字符串 1 中的第二个 NN token 与字符串 2 中的第二个 NN token 进行匹配。
这就是我到目前为止所拥有的..
import java.util.ArrayList;
import java.util.Scanner;
public class TokenMatching {
public static void main(String[] args)
{
ArrayList<String> taggedArray = new ArrayList<String>();
//Example how the string would look like
String string1 = "WRB VBD NN VB IN CC RB VBP NNP";
String string2 = "WRB NN MD PRP VB DT NN IN NNS POS JJ NNS";
taggedArray.add(string1);
taggedArray.add(string2);
//Nested for loop to match taggedArray(i) with taggedArray(j)
for(int i = 0; i< taggedArray.size(); i++)
{
for(int j = i + 1; j < taggedArray.size(); j++)
{
Scanner scan1 = new Scanner(taggedArray.get(i));
int index1 = 0;
while(scan1.hasNext())
{
String token1;
token1 = scan1.next();
System.out.println(token1);
Scanner scan2 = new Scanner(taggedArray.get(j));
int index2 =0;
while(scan2.hasNext())
{
String token2 = scan2.next();
if(token1.equals(token2))
{
int relPosition;
relPosition = Math.abs(index1-index2);
//The print lines help me keep track of what is going on in the loop
System.out.println("Match found.");
System.out.println("Relative position for " + token1 + " : " + relPosition);
}
else
{
System.out.println("No Match Found.");
}
index2++;
}
index1++;
}
}
}
}
}
任何建议都会有很大帮助。谢谢。
最佳答案
- Is there a way to make the Scanner scan for the first occurrence ONLY and move to the next token in string 1
在 if(token1.equals(token2))
中,在 System.out.println("Relativeposition for "+ token1 + 后面添加一个
。输出是 http://ideone.com/2o5Yz 生成的你想要什么?break;
“:”+relPosition);
关于Java:如何让扫描仪仅匹配第一次出现的情况,如果之前已匹配过则跳过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12279214/