[英]How can I compare two strings and try to print out comman latters but i could not avoid to repeat a latter more than once
I am comparing two strings and try to print out comman latters but i could not avoid to repeat a latter more than once. 我正在比较两个字符串,并尝试打印出逗号分隔符,但我无法避免重复重复后者。 here is my code
这是我的代码
public static String getCommonCharacters ( final String a, final String b){
String result="";
for(int i = 0; i < a.length(); i++){
for(int j = 0; j < b.length(); j++)
if(a.charAt(i)==b.charAt(j)){
result +=a.charAt(i);
}
} return result;
the problem is when a = "baac" and b =" fdeabac " then i get out = "aabaac" instead of "abc" or "bca" etc 问题是当a =“ baac”和b =“ fdeabac”时,我退出=“ aabaac”而不是“ abc”或“ bca”等
change the if
condition to: 将
if
条件更改为:
if (a.charAt(i) == b.charAt(j) &&
!result.contains(String.valueOf(a.charAt(i)))) { ... }
Thus, you only perform the statement: 因此,您仅执行以下语句:
result +=a.charAt(i);
if the accumulating string doesn't already contain the character. 如果累积字符串尚未包含字符。
Working code with minor modification to yours: 对您的代码进行了少量修改的工作代码:
public class StringCompare {
public static String getCommonCharacters(final String a, final String b) {
String result = "";
for (int i = 0; i < a.length(); i++) {
for (int j = 0; j < b.length(); j++)
if (a.charAt(i) == b.charAt(j)) {
result += a.charAt(i);
}
}
return result;
}
public static void main(String[] args) {
System.out.println(getCommonCharacters("baac", "fdeabac ").replaceAll(
"(.)\\1{1,}", "$1")); // You could use regular expressions for
// that. Removing repeated characters.
}
}
Output: 输出:
bac
bac
Pattern explanation: 模式说明:
" (.)\\1{1,} " means any character (added to group 1) followed by itself at least once “ (。)\\ 1 {1,} ”表示任何字符(添加到组1),其后至少一个字符
" $1 " references contents of group 1 “ $ 1 ”引用组1的内容
More about Regular Expressions Oracle Docs 有关正则表达式Oracle Docs的更多信息
Hier is another solution: create two new HashSet for each String which we change to charArray, then add them to hashSet with For loops, retainAll() method provide used to remove it's elements from a list that are not contained in the specified collection.@Java Doc by Oracle Last For-Loop used to concatenate char as a strings. Hier是另一种解决方案:为每个String创建两个新的HashSet,将其更改为charArray,然后使用For循环将其添加到hashSet中,retainAll()方法提供了用于从列表中删除指定集合中未包含的元素的方法。 Oracle Last For-Loop的Java Doc用于将char连接为字符串。
String str ="";
Set<Character> s1 = new HashSet<Character>();
Set<Character> s2 = new HashSet<Character>();
for(char c:a.toCharArray()) s1.add(c);
for(char c:b.toCharArray()) s2.add(c);
s1.retainAll(s2);
for(char s:s1) str +=s;
return str;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.