查找文本中的成对字符 [英] Find pairs of characters from a text

查看:45
本文介绍了查找文本中的成对字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,我想查找像"hello you are" 这样的成对字符,答案将是 [he,el,ll,lo,oh,ho,ow,wa,ar,re,ey,yo,ou] ,我尝试了以下操作,但不起作用.我也希望它们是唯一的,但是如果我找到它们,我可能会发现.

I have a file and I want to find pairs of characters like "hello how are you" and the answer would be [he,el,ll,lo,oh,ho,ow,wa,ar,re,ey,yo,ou], I tried the following but it does not work. I also want them to be unique but I will probably find that if I find the pairs.

P.S:是我正在执行程序的文件

P.S: the "result" is the file I am doing the program on

 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 ,这样它才是唯一的,并且可以在单循环中完成

Use an HashSet while storing the results, so that it will be unique and can be done in single loop

String result = "hello how are you".replaceAll("\\s+", "");
HashSet<String> pairs = new HashSet<>();
for (int i = 0; i < result.length() - 1; i++){
     pairs.add(result.charAt(i) + ""+result.charAt(i+1));
}
for(String s: pairs){
    System.out.println(s+",");
}

以上代码段将给出以下输出

The above snippet will give following output

这篇关于查找文本中的成对字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆