Find pairs of characters from a text

Viewed 175

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: 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]);
      }
 }
5 Answers

I would approach it like this:

  1. Remove all spaces from the string you are working with, so that you deal only with pairs.
  2. Use a HashSet to keep all the pairs, why HashSet? Since it is a data container which discards duplicates, through this we remove the need to check whether we already have a pair inside or not.

An example is found below:

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.
    
}

You could do this as follows:

  • Go through the string, one character at a time.
  • When you find an alphabetic character, find the next alphabetic character, that's a pair, store it.
  • Continue.

For example:

Set<String> pairs = new HashSet<>(); // Or LinkedHashSet, if you want them in encounter order.
for (int i = 0; i < input.length(); ++i) {
  // Skip over non-alphabetic characters.
  if (!Character.isAlphabetic(input.charAt(i))) continue;

  // Look for the next alphabetic character:
  for (int j = i + 1; j < input.length(); ++j) {
    // Skip over non-alphabetic characters.
    if (!Character.isAlphabetic(input.charAt(j))) continue;      

    // You've now found a pair.
    pairs.add("" + input.charAt(i) + input.charAt(j));
    break;
  }
}

Ideone demo

This should do the trick -

  char[] input =  "hello how are you".toCharArray();
    Set<String> output = new HashSet<>();

    for (int i = 1; i < input.length; i=i+2)
    {
       output.add(Character.toString(input[i-1])  + Character.toString(input[i]));
    }
    for (String s : output) {
        System.out.println(s);
    }

The use of the HashSet should remove duplicates too.

Hashtable does the magic for you. It is a data container and lets unique value to put in only. This is a fully operable example. Call it with a filename as parameter.

See the code:

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.util.Enumeration;
    import java.util.Hashtable;
    import java.util.Vector;

    public class FindCharPairs 
    {

public static void main(String[] args)throws Exception 
{ 
    
    if(args==null || args.length==0 || args[0]==null)
    {
        System.out.println("Usage:\nFindCharPairs <filename>\n");
        System.exit(1);
    }

    //gets the first parameter
    File file = new File(args[0]);      
    //creates a reader
    BufferedReader br = new BufferedReader(new FileReader(file)); 
  
    //vector to keep the same sequence if it is needed
    Vector<String> vt = new Vector<String>();
    //Hashtable to keep it unique
    Hashtable<String, String> ht = new Hashtable<String, String>();
    String string; 
    String str;
    int to;
 
    //keep reading the file line by line while EOF
    while ((string = br.readLine()) != null) 
    {
        //process the string and put pairs into Hashtable and the Vector from str variable
        to = string.length()-1;
        System.out.println("process line:"+string);
        for(int i=0;i<to;i++)
        {
            str=""+string.charAt(i)+string.charAt(i+1);
            ht.put(str, str);
            vt.add(str);
        }
    } 
    br.close();//close the reader
    
    //display what we have in the Hashtable
    System.out.println("Elements from Hashtable");
    Enumeration<String> en = ht.elements();
    while(en.hasMoreElements())
    {
        System.out.println(en.nextElement());
    }
    //display the pairs in the origin order
    System.out.println("Elements from Vector");
    en = vt.elements();
    while(en.hasMoreElements())
    {
        System.out.println(ht.get(en.nextElement()));
    }
}//end of main
    }

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 enter image description here

Related