RonaldB
RonaldB

Reputation: 29

Java Array String Compare

Hi everyone i'm trying to compare a array and i want to print the letters in common between the position [0] and the [1]

example in the array[0] i have something like a[0]=aokk and in the other position i have one that say a[1]=ok;

i want the problem to print only the letter that are in the position 0 and too in the what i'm doing is

for (int j = 0; j < a[0].length(); j++) {
    for (int i = 0; i < a[1].length(); i++) {
        if (a[0].charAt(i) == b[1].charAt(j)) {
            common += a[0].charAt(i);
        }
    }
}

but i'm getting as a output "okk" when when it should be "ok" because the K is only once in the position [0]

Upvotes: 1

Views: 231

Answers (7)

Anonymous
Anonymous

Reputation: 86379

There’s a lovely wealth of solutions already, each with their strengths and weaknesses. I’ll put in my suggestion. I am assuming that order of letters is not important, but if a letter occurs twice in each string, it must also occur twice in the result.

/** @return chars common to a[0] and a[1] */
public static String commonChars(String[] a) {
    int[] charCounts = new int[256];
    for (int index = 0; index < a[0].length(); index++) {
        charCounts[a[0].charAt(index)]++;
    }
    StringBuilder result = new StringBuilder(a[0].length());
    for (int index = 0; index < a[1].length(); index++) {
        if (charCounts[a[1].charAt(index)] > 0) {
            result.append(a[1].charAt(index));
            charCounts[a[1].charAt(index)]--;
        }
    }
    return result.toString();
}

Strengths in my own judgement: Takes into account that a letter may occur twice (as in Button and Butter, or letter and bitter). Fairly efficient (which probably doesn’t matter). And in case it matters, the letters generally come out in the same order as found in a[1].

Weakness I’m aware of: breaks down with an ArrayIndexOutOfBoundsException if either string contains a character outside the Latin-1 range (0 through 255) or a is shorter than 2.

Upvotes: 0

Anands23
Anands23

Reputation: 790

Try this :

1.Assuming in your case,that in String array , a[0] has maximum length
2.Of course, you can get the maximum length from the string array you can choose the max length and you can modify the length and do according to your requirement.                                
3. For now, check the following :

public static void main(String[] args) 
{

String a[]={"aokk","ok"};
String common = "";
 for(int i=0;i < a[1].length();i++)
 {
  for(int j=0; j<a[0].length();j++) 
  {
    if(a[1].charAt(i) == a[0].charAt(j) && common.indexOf(a[0].charAt(j))<0)
    {
       common = common + a[0].charAt(j);
    }
  }
 }
  System.out.println(common);
}

Upvotes: 0

user3795373
user3795373

Reputation: 13

If ordering is not important then you can use below code. You can sort both of the array and then alter merge sort for comparison common in strings.

public static String commonInArray(char[] char1, char[] char2) {
    int i = 0, j = 0;

    String common = "";

    while(i < char1.length) {
        if(char1[i] == char2[j]) {
            common += char1[i];
            i++;
            j++;
        } else if(char1[i] > char2[j]) {
            j++;
        } else {
            i++;
        }
    }

    return common;
} 

public static void main (String[] args) {
    // Strings in array for comparison
    String[] array = {"bitter","letter"};

    char[] char1 = array[0].toCharArray();
    Arrays.sort(char1);

    char[] char2 = array[1].toCharArray();
    Arrays.sort(char2);

    String common;

    if(char1.length > char2.length) {
        common = commonInArray(char1, char2);
    } else {
        common = commonInArray(char2, char1);
    }

    System.out.println(common);
}

Alternate Solution:

1) Store first string in linked list

2) Traverse second string

3) Remove common element from linked list

    String[] a = {"aokk", "ok"};
    String common = "";

    LinkedList<Character> store = new LinkedList<Character>();

    for(int i = 0; i < a[0].length(); i++) {
        store.add(a[0].charAt(i));
    }

    for (int i = 0; i < a[1].length(); i++) {
        if(store.contains(a[1].charAt(i))) {
            common += a[1].charAt(i);
            store.remove(store.indexOf(a[1].charAt(i)));
        }
    }

    System.out.println(common);

Upvotes: 0

Yash Mehta
Yash Mehta

Reputation: 213

Here is what you need:

import java.util.ArrayList;
import java.util.List;

class Solution{
    public static void main(String args[]){
        String arr[] = {"aokk","ok"};
        List<Integer> index = new ArrayList<Integer>();
        for(int i=0;i<arr[0].length();i++){
            for(int j=0;j<arr[1].length();j++){
                if(arr[0].charAt(i)==arr[1].charAt(j) && index.contains(j)==false){
                    System.out.print(arr[0].charAt(i)); //print if it matches
                    index.add(j);//add index to list so it won't count again
                    break;
                }
            }
        }
    }
}

Upvotes: 0

Maxwell
Maxwell

Reputation: 13

public class PrintCommonLetters {

    public static void main(String[] args) {

        // Strings in array for comparison
        String[] array = {"ok","aokk", "ko"};

        for(int i = 0; i < array.length - 1; i++)
        {
            for(int j = i + 1; j <= array.length - 1; j++)
            {   
                // Compare which string is longer
                if(array[i].length() > array[j].length())
                {
                    // Found substring array[j] in array[i]
                    if(array[i].contains(array[j]))
                        System.out.println(array[j]);
                }
                else
                {
                    // Found substring array[i] in array[j]
                    if(array[j].contains(array[i]))
                        System.out.println(array[i]);
                }               
            }
        }
    }
}

Upvotes: 0

Bruce Lin
Bruce Lin

Reputation: 76

The problem of this algorithm is that you are comparing two strings with different length. In this case, the string with a shorter length finishes its loop earlier than another string does, so the shorter one its index remains at the last element, which is "k". Another string its loop still keeps going on, and when it reaches the letter "k", your if condition is true(since "k" == "k"), that's why you will have double k.

Upvotes: 1

Dale
Dale

Reputation: 191

try remove duplicate from common:

List<Character> list = new ArrayList<Character>();
for (char ch : common.toCharArray()) {
            list.add(ch);
}
return new HashSet<>(list).toString();

Upvotes: 0

Related Questions