private String removeDuplicates(String userKeyword){
int wordLength = userKeyword.length();
int lengthCounter;
for (lengthCounter=0; lengthCounter<wordLength; lengthCounter++){
if (userKeyword.charAt(lengthCounter) != userKeyword.charAt(lengthCounter + 1)){
String revisedKeyword = "" + userKeyword.charAt(lengthCounter);
userKeyword = revisedKeyword;
}
}
return userKeyword;
}
我对java真的很陌生。我们还没有使用字符串构建器、字符串缓冲区、数组等...我们甚至还没有开始循环,但我认为这将是最简单的使用方法...请帮忙。
最佳答案
有无数种方法可以做到这一点。在您已建立的工具集范围内找到您自己的解决方案就是学习编程的全部内容。这是一个可以让您思考的可能解决方案:
创建一个Set,默认情况下只能保存唯一值
Set<Character> mySet = new HashSet<Character>();
然后循环字符串中的字符,将每个字符添加到 mySet
mySet.add(c);
完成后,您的集合将有一个唯一且按顺序排列的字符列表,您可以使用以下命令打印它们
for (char c : mySet) {
System.out.println(c)
}
编辑:
这是使用嵌套循环的简单设置
String s = "einstein"; //This is the word you will look for duplicates in
String temp = ""; //In this string, you will add characters that are not duplicates
boolean isDuplicate = false; //This will reset every out iteration
我使用一个困难的例子来让事情变得简单。请理解,字符串 temp
将以空开始,但是当整个过程完成后,您的目标是让 temp
具有与爱因斯坦相同的字符,并且没有重复。类似于 stein
public static void main (String[] args) {
String s = "einstein";
String temp = "";
boolean isDuplicate = false;
for (int i = 0; i < s.length(); i++) {
isDuplicate = false;
char comparisonChar = s.charAt(i);
for (int j = i + 1; j < s.length(); j++) {
char nextChar = s.charAt(j);
if (comparisonChar == nextChar) isDuplicate = true;
}
if (!isDuplicate) temp = temp + comparisonChar;
}
System.out.println(temp); //should print `stein`
}
}
现在我还没有对此进行测试,因此它可能存在错误,但请在心里仔细浏览并尝试理解它。困惑时问我。
关于java - 删除字符串中的重复字符(用户输入的关键字),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18157378/