我有一个文件,我想查找像 "hello how are you"
这样的字符对答案是[he,el,ll,lo,oh,ho,ow,wa,ar,re,ey,yo,ou]
,我尝试了以下方法,但不起作用。我也希望它们是独一无二的,但如果我找到配对,我可能会发现这一点。
PS:“结果”是我正在执行程序的文件
int[][] pairs = new int[result.length()][];
for (int i = 0; i < result.length(); i++)
{
for (int j = 0; j < result.length(); j++)
{
pairs[i][j] = j + 1;
System.out.println(pairs[i][j]);
}
}
最佳答案
我会这样处理:
- 删除您正在使用的字符串中的所有空格,以便仅处理对。
- 使用 HashSet 来保存所有对,为什么是 HashSet?由于它是一个丢弃重复项的数据容器,因此我们无需检查内部是否已经有一对。
下面是一个示例:
String formattedString = result.replace(" ", ""); // removing all the spaces from our result (which could be a line of the file)
HashSet<String> pairSet = new HashSet(); // Initializing an empty HashSet
for (int i = 0; i < result.length() - 1; i++)
{
final String tmp = formattedString.substring(i, 2); // Give me a pair of 2 characters starting from i (so in the first index then second and so on)
pairSet.add(tmp); // We add this to our set, if it is already contained, it is discarded.
}
关于java - 从文本中查找字符对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66134903/