简体   繁体   English

Java 数组字符串比较

[英]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]大家好,我正在尝试比较一个数组,我想打印位置 [0] 和 [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;例如,在数组 [0] 中,我有类似 a[0]=aokk 的内容,而在另一个位置,我有一个说 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我希望问题只打印位置 0 中的字母,而且我正在做的是

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]但是当它应该是“ok”时,我得到了一个输出“okk”,因为 K 在位置 [0] 只有一次

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".在这种情况下,长度较短的字符串比另一个字符串更早完成循环,因此较短的字符串的索引保留在最后一个元素,即“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.另一个字符串的循环仍在继续,当它到达字母“k”时,您的 if 条件为真(因为“k”==“k”),这就是为什么您将拥有双倍 k。

try remove duplicate from common:尝试从 common 中删除重复项:

List<Character> list = new ArrayList<Character>();
for (char ch : common.toCharArray()) {
            list.add(ch);
}
return new HashSet<>(list).toString();
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]);
                }               
            }
        }
    }
}

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 1) 将第一个字符串存储在链表中

2) Traverse second string 2) 遍历第二个字符串

3) Remove common element from linked list 3) 从链表中删除公共元素

    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);

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

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);
}

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] .万一重要,字母通常以与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.我知道的弱点:如果任一字符串包含超出 Latin-1 范围(0 到 255)或a小于 2 的字符,则会出现ArrayIndexOutOfBoundsException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM