2013-03-13 83 views
0

我正在为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循环,但我不知道究竟是什么问题。现在,它将打印出传入的整个字符串,当它应该打印每个字母只有一次。有人可以帮忙吗?

+0

你能举出输入文本,输入模式和正确输出的例子吗? – ghdalum 2013-03-13 20:53:31

回答

3

而不是计算每个字符的出现次数,请使用Set<Character>。一个集合包含独特的元素,所以你不会有重复的方式。

您也可以通过做mySet.toArray(new String[mySet.size()]);或只是mySet.toArray(new String[0]);

+1

似乎是我的功课。如果没有,是的,使用'Set'并最大化快乐。 – mgarciaisaia 2013-03-13 20:50:03

+0

我会以这种方式执行此操作:? Set mySet = new Set (t); 其中t是用户输入的字符串? 谢谢! – Mouse 2013-03-13 20:52:43

+0

@Mouse,不,你仍然需要迭代字符串中的字符,然后将它们添加到'Set'中。 – 2013-03-13 20:54:11

0

你的代码是不容易阅读转换Set到一个数组。您可以考虑使用以下算法。

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之外与%运营商。

+0

谢谢你的帮助,我得到了它的工作。 :) – Mouse 2013-03-13 21:10:02

相关问题