只在String中获取一次字母

时间:2013-03-13 20:44:44

标签: java char

我正在为Horspool的算法编写一个Java程序,并且遇到了一些麻烦。我正在尝试创建一个字符数组,将每个字母保存在一个字符串中,但我不希望重复这些字母。现在这是我的代码:

public static void main(String[] args) 
{
    Scanner scanIn = new Scanner (System.in);

    int count = 0;

    int count2 = 0;

    int inc = 0;

    //The text to search for the phrase in
    String t = "";

    //The phrase/pattern to search for
    String p = "";

    System.out.println(" ");
    System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    System.out.println("Harspool's Algorithm: ");
    System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    System.out.println(" ");
    System.out.println("Please enter the full text: ");
    t = scanIn.nextLine();
    System.out.println("Please enter the pattern to search for: ");
    p = scanIn.nextLine();

    char[] text = new char[t.length()];
    char[] pattern = new char[p.length()];
    char[] alphabet = new char[t.length()];

    for (int i = 0; i < alphabet.length; i++)
    {
        alphabet[i] = ' ';
    }


    for (int i = 0; i < text.length; i++)
    {
        text[i] = t.charAt(i);
    }

    for (int i = 0; i < pattern.length; i++)
    {
        pattern[i] = p.charAt(i);
    }

    while (inc < text.length)
    {
        for (int j = 0; j < text.length; j++)
        {
            if (text[inc] != alphabet[j])
            {
                count++;
            }
            if (count == p.length() - 1 && count2 < text.length)
            {
                alphabet[count2] = text[inc];
                count2++;
                count = 0;
                inc++;
            }
        }
    }

    for (int i = 0; i < alphabet.length; i++)
    {
        System.out.print(alphabet[i]);
    }
}

我认为问题出在while循环中,但我无法弄清楚到底出了什么问题。现在,它将打印出传入的整个字符串,它应该只打印每个字母一次。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:3)

使用Set<Character>而不是计算每个字符的出现次数。集合包含唯一元素,因此您不会有这样的重复。

您还可以SetmySet.toArray(new String[mySet.size()]);

mySet.toArray(new String[0]);转换为数组

答案 1 :(得分:0)

您的代码不易阅读。您可以考虑使用以下算法。

int ccount[256];
int ii;
for(ii=0;ii<256;ii++) ccount[ii]=0;
for (ii = 0; ii < text.length; ii++)
{
    ccount[t.charAt(i)%256]++;
}
for (ii = 0; ii<256; ii++) {
    if(ccount[ii]>0) System.out.printf("%c", ii);
}

编辑 - 确保ccount已初始化,并使用%运算符捕获0-255范围之外的字符。

相关问题