gpt4 book ai didi

java - 只获取字符串中的每个字母一次

转载 作者:行者123 更新时间:2023-12-01 23:57:11 25 4
gpt4 key购买 nike

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

最佳答案

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

您还可以转换 Set通过执行 mySet.toArray(new String[mySet.size()]); 到数组或者只是 mySet.toArray(new String[0]);

关于java - 只获取字符串中的每个字母一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15396091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com