Search code examples
javacontainsmaskingstartswithcontainskey

How to use startsWith or contains method with string or string array?


My address as string contains this details

String address = "S/O: KANTH MEIPPEN PACHU, N-2345, THAMBULI";

Here masking to be implemented for the above mentioned address line in below format

if the address line starts with S/O, D/O, W/O, C/O it should mask address line like

S/O: KA******************************BULI

ie,. after any of mentioned string masking to be done on the address leaving first four and last four chars

We can use startsWith method but we cannot pass array inside it to check with address string also how to configure the S/O, D/O, W/O, C/O in a single constant with separator to check as it will reduce the code mess up

Here is the java code:

public static void main(String ars[]) throws Exception {
    String address = "S/O: KANTH MEIPPEN PACHU, N-2345, THAMBULI;
    String[] words = {
        "S/O",
        "D/O",
        "W/O",
        "C/O"
    };
    String joined = Arrays.toString(words);
    //list.stream().filter(p -> p.getName().equals(name)).findFirst().isPresent();
    //  ArrayList<String> list = new ArrayList<>(Arrays.asList(address.split("|")));
    System.out.println("Address:::: " + joined);
    //list.stream().anyMatch((a) -> a.startsWith(words));
    if (address.startsWith("S/O") {
            String separator = "S/O";
            int sep = address.indexOf(separator);
            String adress = address.substring(sep + separator.length());
            System.out.println("Address:::: " + adress);
            String masks = String.join("", Collections.nCopies(adress.length() - 8, "*"));
            System.out.println("Mask::: " + masks);
            adress = separator + adress.substring(0, 4) + masks + adress.substring(adress.length() - 4);
        }
    }

Solution

  • I have updated your code to use Regex

    public static void main(String[] args) {
            String address = "S/O: KANTH MEIPPEN PACHU, N-2345, THAMBULI";
            String salutation = "^[SDWC][//]O";
            Pattern pattern = Pattern.compile(salutation);
            Matcher matcher = pattern.matcher(address);
            if (matcher.find()) {
                String group = matcher.group();
                int sep = address.indexOf(group);
                String addressStr = address.substring(sep + group.length());
                System.out.println("Address:::: " + addressStr);
                String masks = String.join("", Collections.nCopies(addressStr.length() - 8, "*"));
                System.out.println("Mask::: " + masks);
                addressStr = group + addressStr.substring(0, 4) + masks + addressStr.substring(addressStr.length() - 4);
                System.out.println(addressStr);
            }
        }