我正在尝试从字符串中删除重复的常用字符,但问题只是最后一个常见字符,在这种情况下,y被删除,所有其他常见字符都按原样显示。我没有任何例外。
public class stringCompare {
private static String s;
private static char[] c;
private static boolean[] b;
public static void judge(boolean flag , int l){
b[l] = flag;
}//judge
public static void main(String[] args) {
s = "unlucky unlucky unlucky unlucky";
c = new char[s.length()];
b = new boolean[s.length()];
int j;
System.out.println(s.length());
for(int i=0 ; i<s.length() ; i++){
c[i] = s.charAt(i);
System.out.println(c[i]);
for(j=0 ; j<s.length() ; j++){
System.out.println(c[j]);
if(c[i] == s.charAt(j)){
judge(true , i);
}//if
else if(c[i] != s.charAt(j)){
judge(false , i);
}//else if
}//for
}//for
StringBuilder sb = new StringBuilder(s.length());
for(int k=0 ; k<b.length ; k++){
System.out.println(b[k] +"===="+k);
if(b[k] == false){
sb.append(c[k]);
}//if
}//for
System.out.println(sb.toString());
}//main
}//stringCompare
Output from the program -
unluck unluck unluck unluck
但我期待输出为 - 不吉利
答案 0 :(得分:0)
试试这个逻辑
StringBuilder sb=new StringBuilder();
String s = "unlucky unlucky unlucky unlucky";
char[] inp_cpy=s.toCharArray();
for( char x : inp_cpy)
{
if(!sb.ToString().Contains(""+x))
{
sb.append(x);
}
}
System.out.println(sb.toString());
答案 1 :(得分:0)
此代码打印&#34; unlcky&#34;,即删除所有重复的字符。我明白这是你的问题。如果&#34; indexOf&#34;不允许那么你应该用一个在字符串中搜索字符的循环替换它。
public class stringCompare {
private static String s;
public static void main(String[] args) {
s = "unlucky unlucky unlucky unlucky";
StringBuilder result = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
String currentChar = s.substring(i,i+1);
if (result.indexOf(currentChar)==-1) {
result.append(currentChar);
}
}
System.out.println(result.toString());
}
}
答案 2 :(得分:0)
如果排序是一个值得关注的问题,你可以使用LinkedHashSet,否则使用TreeSet或HashSet。
import java.util.Arrays;
import java.util.LinkedHashSet;
public class StringCompare{
public static void main(String[] args) {
String s = "unlucky unlucky unlucky unlucky";
LinkedHashSet<Character> linkedhashset = new LinkedHashSet<Character>();
for (int i = 0; i < s.length(); i++) {
if(s.charAt(i) != ' ')
linkedhashset.add(s.charAt(i));
}
System.out.println(Arrays.toString(linkedhashset.toArray()));
linkedhashset.forEach(System.out::print);
}
}
输出是:
[u, n, l, c, k, y]
unlcky