0

I have to remove Salutations like "C/O, C/o,c/o,S/O,S/o,s/o" etc from a string.These salutations comes a third party service. The service can return anything form these. How to do this effectively. I am doing this by using below code:

if(name.contains("C/O")){
            name = name.replace("C/O", "").trim();
            System.out.println("name: "+name);
        }else if(name.contains("S/O")){
            name = name.replace("S/O", "").trim();
            System.out.println("name: "+name);
        }else if(name.contains("c/o")){
            name = name.replace("c/o", "").trim();
            System.out.println("name: "+name);
        }else if(name.contains("S/o")){
            name = name.replace("S/o", "").trim();
            System.out.println("name: "+name);
        }

Any better approach to do this. Please suggest.

5
  • You should probably store all possible salutations in an array and loop through them, instead of having multiple if/else statements. Commented Jan 18, 2018 at 17:22
  • @Am_I_Helpful I can get any number of salutations and in any format like "D/O , d/o, D/o,W/o,H/O" etc. Should I put these many if blocks Commented Jan 18, 2018 at 17:22
  • 1
    you can try using regular expression in String.replaceAll() Commented Jan 18, 2018 at 17:23
  • 2
    In every case you basically do the same. Instead you may use regex and a single call to something like replaceAll("(?i)(C/O|S/O)", ""). The expression removes everything which is C/O or S/O, case insensitive. Then your code is only name = name.replaceAll("(?i)(C/O|S/O)", ""); and that's it. Commented Jan 18, 2018 at 17:25
  • 1
    You don't really need to check if name.contains(some_string) before performing the substitution name.replace(some_string, ""). Commented Jan 18, 2018 at 17:25

2 Answers 2

2

Say hello to regex!

name = name.replaceAll("(?i)[cs]/o\\s*", "");

The regex breakdown:

  • (?i) means ignore case
  • [cs] means "c" or "s"
  • \\s* means all white space following (if any)
Sign up to request clarification or add additional context in comments.

Comments

1

A traditional way to do this could look as follows:

String[] salutations = {"C/O", "S/O", "c/o", "S/o"};
for (String salutation : salutations)
{
    name = name.replace(salutation, "").trim();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.