java - 从文本中查找字符对

标签 java arrays

我有一个文件,我想查找像 "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]);
      }
 }

最佳答案

我会这样处理:

  1. 删除您正在使用的字符串中的所有空格,以便仅处理对。
  2. 使用 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/

相关文章:

java - 尝试创建错误检查方法,以使计数器在计数器为0时不递减

python - 如何设置具有给定列表位置的嵌套 python 字典的 "nth"元素?

arrays - 修改结构中数组的最佳方法?

c# - 在 C# 中初始化 int[][,]

arrays - F#查找2个数组/列表之间的丢失元素

java - 每天在特定时间将项目添加到房间数据库

java - 表单验证失败时填充模型的最佳方法?

java - 为什么下面的代码没有为变量创建一个新值?

java - 为什么这个线程代码不能在 GUI 中正常工作? [Java Swing] [线程]

c# - 无论如何,是否有 DllImport 函数从作为字节数组加载到 RAM 中的 native dll?