Reputation: 3380
I have two different string String A="example"; String B="example";
if concat both the string i am getting examplexample.
Is there any possibility to avoid repetition of string with same name..??
Upvotes: 0
Views: 1169
Reputation: 1536
Just create a Set (It has mathematics set behaviour, it won't accept the duplicate objects)
Set<String> strings = new HashSet<String>();
//Fill this set with all the String objects
strings.add(A)
Strings.add(B)
//Now iterate this set and create a String Object
StringBuilder resultBuilder = new StringBuilder();
for(String string:Strings){
resultBuilder.append(string);
}
return resultBuilder.toString()
`
Upvotes: 1
Reputation: 82948
You can. Try something like this
private String concatStringExample1(String firstString, String secondString) {
if(firstString.equalsIgnoreCase(secondString)) { // String matched
return firstString; // or return secondString
} else { // Not matched
return firstString.concat(secondString);
}
}
or
private String concatStringExample2(String firstString, String secondString) {
if(firstString != null && firstString != null ) {
if(firstString.toLowerCase().indexOf(secondString.toLowerCase()) >= 0)
return firstString;
else if(secondString.toLowerCase().indexOf(firstString.toLowerCase()) >= 0)
return secondString;
else
return firstString.concat(secondString);
} else {
return "";
}
}
Upvotes: 1
Reputation: 114767
The Strings are not different, the same String object is assigned to two different variables ("two pointers to the same memory address").
Consider dumping all strings to a Set
before concatenating, this avoids duplicates in the concatenated sequence:
Set<String> strings = new HashSet<String>();
StringBuilder resultBuilder = new StringBuilder();
for (String s:getAllStrings()) { // some magic to get all your strings
if (strings.contains(s))
continue; // has been added already
resultBuilder.append(s); // concatenate
strings.add(s); // put string to set
}
String result = resultBuilder.toString();
Upvotes: 1
Reputation: 240880
How about this ?
if(!a.equals(b)){// or if needed use contains() , equalIgnoreCase() depending on your need
//concat
}
Upvotes: 3