In java, how to add a line ignoring duplicates

I have the line "ABC, D", now I want to write an append(initialStr, currStr ) method append(initialStr, currStr ) that adds currStr to initailStr only if currstr is not already present in initialStr . I tried a method that divides a comma, but since my string contains a comma, so the method does not work for me. Any help would be greatly appreciated.

+4
source share
4 answers
 String appendIfNotPresent(String initial, String curr) { if (initial.contains(curr)) return initial; else return initial + curr; } 
+6
source

I would write it so that it works 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; } } 
+2
source

One option is to use indexOf() to determine if one row is contained in another.

  int i = initialStr.indexOf(currStr) if(i != -1){ //go ahead and concatenate } 
0
source

You can use indexOf to search for currStr. If the indexOf method returns -1, then there is no match. Another number will be the starting location of the substring.

 if(initialStr.indexOf(currStr) == -1) { initialStr += currStr; } 

Alternatively, if it doesn't matter, you can add toLowerCase () or toUpperCase () in the above code example:

 if(initialStr.toLowerCase().indexOf(currStr.toLowerCase()) == -1) { initialStr += currStr; } 

If you have a lot of string operations, I recommend looking at the StringUtils class from the Apache Commons Lang library. It provides many useful methods. Here is the API link: http://commons.apache.org/lang/api-release/org/apache/commons/lang/StringUtils.html

0
source

All Articles