Home > Mobile >  Replace part of substring with specific characters based on delimiter
Replace part of substring with specific characters based on delimiter

Time:06-07

String s = "abc//jason:[email protected]/";

I want to replace all the substring before and after ":" delimiter with "......."

I want my final output to be :

"abc//.....:[email protected]:212/"

I tried doing this since there is a second : in the string it gets messed up, is it there better way to be able to get my output:

  String [] headersplit;
            headersplit = s.split(":");

CodePudding user response:

If you want to locate only symbols between "//" and "@" then algorithm is simple, provided that mention symbols are compulsory.

public class Main {
    public static void main(String[] args) {
        String s = "abc//jason:[email protected]/";

        System.out.println(replaceSensitiveInfo(s));
    }

    static String replaceSensitiveInfo(String src) {
        int slashes = src.indexOf("//");
        int colon = src.indexOf(":", slashes);
        int at = src.indexOf("@", colon);

        StringBuilder sb = new StringBuilder(src);

        sb.replace(slashes   2, colon, ".".repeat(colon - slashes - 2));
        sb.replace(colon   1, at, ".".repeat(at - colon - 1));

        return sb.toString();
    }
}

CodePudding user response:

Not the best way but it works for your example and should work for others:

String s = "abc//jason:[email protected]:212/";

String result = replaceSensitiveInfo(s);

private String replaceSensitiveInfo(String info){

    StringBuilder sb = new StringBuilder(info);

    String substitute = ".";

    int start = sb.indexOf("//")   2;
    int end = sb.indexOf(":");

    String firstReplace = substitute.repeat(end - start);

    sb.replace(start, end, firstReplace);

    int start2 = sb.indexOf(":")   1;
    int end2 = sb.indexOf("@");

    String secondReplace = substitute.repeat(end2 - start2);
    sb.replace(start2, end2, secondReplace);

    return sb.toString();
}
  • Related