我如何在新数组中存储匹配字符

时间:2014-10-10 05:24:50

标签: java arrays

我正在尝试将元素存储在新数组中。以下是我的代码。

for (int i = 0; i < namea1.length; i++) {
    for (int j = 0; j < namea2.length; j++) {
        if (namea1[i] == namea2[j]) {
            // ans=new char[shojib[i]];
            count++;
        }
    }
}

我的数组定义如下。

String name1 = "shojib";
String name2 = "farhana";
int count = 0;
char[] namea1 = name1.toCharArray();
char[] namea2 = name2.toCharArray();

我想将所有匹配的字符存储到新数组中。

4 个答案:

答案 0 :(得分:2)

如果只需要唯一匹配字符,请使用Set

示例代码:

import java.util.HashSet;
import java.util.Set;

public class IntersectionChar {

    public static void main(String[] args) {
        findMatchingChars("shojib", "farhana");
        findMatchingChars("one", "onetwothere");
        findMatchingChars("temp", "test");
        findMatchingChars("dis", "connected");
        findMatchingChars("null", "empty");
    }

    private static void findMatchingChars(String a, String b) {
        Set<Character> namea1Chars = new HashSet<Character>();
        Set<Character> namea2Chars = new HashSet<Character>();

        for (char c : a.toCharArray()) {
            namea1Chars.add(c);
        }

        for (char c : b.toCharArray()) {
            namea2Chars.add(c);
        }

        namea1Chars.retainAll(namea2Chars);

        System.out.println("Common Chars in " + a + " & " + b + " are => " + namea1Chars);
    }
}

输出将是:

Common Chars in shojib & farhana are => [h]
Common Chars in one & onetwothere are => [e, n, o]
Common Chars in temp & test are => [e, t]
Common Chars in dis & connected are => [d]
Common Chars in null & empty are => []

如果要捕获所有匹配项,请改用List(尽管会对性能产生影响:

示例代码:

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

public class IntersectionChar {

    public static void main(String[] args) {
        findMatchingChars("shojib", "farhana");
        findMatchingChars("one", "onetwothere");
        findMatchingChars("tempt", "test");
        findMatchingChars("dis", "connected");
        findMatchingChars("null", "empty");
    }

    private static void findMatchingChars(String a, String b) {
        List<Character> namea1Chars = new ArrayList<Character>();
        List<Character> namea2Chars = new ArrayList<Character>();
        for (char c : a.toCharArray()) {
            namea1Chars.add(c);
        }

        for (char c : b.toCharArray()) {
            namea2Chars.add(c);
        }
        namea1Chars.retainAll(namea2Chars);
        System.out.println("Common Chars in " + a + " & " + b + " are => " + namea1Chars);
    }
}

输出:

Common Chars in shojib & farhana are => [h]
Common Chars in one & onetwothere are => [o, n, e]
Common Chars in tempt & test are => [t, e, t]
Common Chars in dis & connected are => [d]
Common Chars in null & empty are => []

您还可以使用Map来获得更好的效果

示例代码:

import java.util.HashMap;
import java.util.Map;

public class IntersectionChar {

    public static void main(String[] args) {
        findMatchingChars("shojib", "farhana");
        findMatchingChars("one", "onetwothere");
        findMatchingChars("tempt", "test");
        findMatchingChars("dis", "connected");
        findMatchingChars("null", "empty");
    }

    private static void findMatchingChars(String a, String b) {
        System.out.print("Common Chars in " + a + " & " + b + " are => [");
        Map<Character, Integer> aCharCount = new HashMap<Character, Integer>();

        for (char c : a.toCharArray()) {
            if(aCharCount.containsKey(c)) {
                aCharCount.put(c, aCharCount.get(c) + 1);
            } else {
                aCharCount.put(c, 1);
            }
        }

        for (char c : b.toCharArray()) {
            if(aCharCount.containsKey(c)) {
                System.out.print(c + ", ");
                if (aCharCount.get(c) == 1) {
                    aCharCount.remove(c);
                } else {
                    aCharCount.put(c, aCharCount.get(c) - 1);
                }
            }
        }
        System.out.println("]");
    }
}

输出:

Common Chars in shojib & farhana are => [h, ]
Common Chars in one & onetwothere are => [o, n, e, ]
Common Chars in tempt & test are => [t, e, t, ]
Common Chars in dis & connected are => [d, ]
Common Chars in null & empty are => []

答案 1 :(得分:0)

尝试使用ArrayList

public static void main(String[] args) {

        String name1 = "sfhojib";
        String name2 = "farhana";
        int count = 0;
        char[] namea1 = name1.toCharArray();
        char[] namea2 = name2.toCharArray();

        List list = new ArrayList();

        for (int i = 0 ; i < namea1.length ; i++) {
            for (int j = 0 ; j < namea2.length ; j++) {
                if (namea1[i] == namea2[j]) {
                    list.add(namea1[i]);
                }
            }

        }

        for (int i = 0 ; i < list.size() ; i++) {
            System.out.println(list.get(i));
        }
    }

<强>输出

f
h

答案 2 :(得分:0)

尝试使用ArrayList。试试以下..

List<Character> match = new ArrayList<Character>();

//...
// If chars are matching
match.add(namea1[i]);

答案 3 :(得分:0)

在循环外创建数组,或者每次获得匹配的char时都会创建一个新数组。

您可以使用ArrayList<Character>,因为您不确定数组的大小(然后使用list.toArray(...)),但每次使用时,您的原始字符都会自动装箱并取消装箱从列表中添加/获取。如果您不想这样做,最好的选择是使用包含匹配项的char[]最长名称的长度,然后手动修剪它。

至于匹配,您可以将该字母添加到列表中,然后将其从每个单词中删除,尽管您需要某种“空”字符来替换该字母,而您知道这些字母不会是任何名称。

不使用ArrayList

char[] name1 = "shojaaaaib".toCharArray();
char[] name2 = "farhana".toCharArray();
char[] matches = new char[name2.length];
final char placeHolder = '~';

firstName:
for(int i = 0; i < name1.length; i++)
    for(int j = 0; j < name2.length; j++)
        if(name1[i] == name2[j])
            for(int k = 0; k < matches.length; k++) //add to matches index if possible
                if(matches[k] == 0) { //if not set yet
                       matches[k] = name1[i];
                    name1[i] = name2[j] = placeHolder;
                    continue firstName;
                }

System.out.println(matches);

这将打印

haaa

由于有1个匹配的h和2个匹配的a s