I have string say "ABC,D" , now I wish to write a method append(initialStr, currStr ) which appends currStr to initailStr only if currstr is not already present in initialStr. I tried a method which splits with comma, but since my string contains comma so that method doesn't works for me. Any help will be greatly appreciated.
views:
132answers:
5String appendIfNotPresent(String initial, String curr)
{
if (initial.contains(curr))
return initial;
else
return initial + curr;
}
One option is to use indexOf() to determine if one string is contained in another.
int i = initialStr.indexOf(currStr)
if(i != -1){
//go ahead and concatenate
}
You can use indexOf to search for currStr. If the indexOf method returns -1, then there is no match. Any other number will be the starting location of the substring.
if(initialStr.indexOf(currStr) == -1) {
initialStr += currStr;
}
Also, if case doesn't matter you can add toLowerCase() or toUpperCase() to the above code sample:
if(initialStr.toLowerCase().indexOf(currStr.toLowerCase()) == -1) {
initialStr += currStr;
}
If you have a lot of string operations to perform, I recommend looking at the StringUtils class from the Apache Commons Lang library. It provides a lot of useful methods. Here is a link to the API: http://commons.apache.org/lang/api-release/org/apache/commons/lang/StringUtils.html
Maybe an overkill for you but I asked a similar question before,
http://stackoverflow.com/questions/1285434/efficient-algorithm-for-string-concatenation-with-overlap
I'd write it like so, to make it work for null values:
String appendIfNotContained(String initial, String curr) {
if (initial == null) {
return curr;
} else if (curr == null) {
return initial;
} else {
return initial.contains(curr) ? initial : initial + curr;
}
}