tags:

views:

132

answers:

5

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.

+6  A: 
String appendIfNotPresent(String initial, String curr)
{
   if (initial.contains(curr))
     return initial;
   else
     return initial + curr;
}
Click Upvote
Minor it: the name 'append' has a well-established meaning, which differs from this. I'd suggest something like "appendIfNotPresent".
CPerkins
Good idea, i've fixed that
Click Upvote
A: 

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
 }
Vincent Ramdhanie
A: 

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

hoffmandirt
+1  A: 

Maybe an overkill for you but I asked a similar question before,

http://stackoverflow.com/questions/1285434/efficient-algorithm-for-string-concatenation-with-overlap

ZZ Coder
+1  A: 

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;
      }
   }
JRL
Why the downvote?
JRL